laravel 的 eloquent 问题寻求帮助

2017-01-10 10:46:12 +08:00
 solaro

也许需求: 1.需要获取订单和订单的商品详情 2.表 order 、 goods 、 barcode

现在: order hasMany goods 、 goods hasOne barcode

怎么写链式?

Order::with('goods')->get();

Order 模型里: function goods() { return $this->hasMany(Goods::class, 'id', 'id'); }

Goods 模型里: function barcode() { return $this->hasOne(Barcode::class, 'id', 'id'); }

现在懵逼了,不会用。。

1138 次点击
所在节点    问与答
5 条回复
ylsc633
2017-01-10 10:54:40 +08:00
github 随便找个博客,看下他们的 分类 帖子 评论
或者 权限 角色 用户 关系..
phpcxy
2017-01-10 11:00:12 +08:00
```
Order::with('goods.barcode')->get();
```
holyghost
2017-01-10 11:00:18 +08:00
https://laravel.com/docs/5.3/eloquent-relationships

你得送我一个感谢你知道吗
solaro
2017-01-10 17:11:51 +08:00
@holyghost 没有用,用不了。。。 hasManyThrough 吗?

我最后用蠢办法
$order_arr = $order->toArray();
foreach ($order_arr as &$order) {
foreach ($order['goods'] as &$goods) {
$barcode = Barcode::where('xxx', xxxx)->first();
// XXXXBBBBCCCC
}
}

return $order_arr;

完全没有性能考量呢。。
holyghost
2017-01-10 17:29:25 +08:00
@solaro 会有 N+1 的问题吧,不过不重要,你都用 PHP 了你还怕啥。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/333526

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX