gpt4 book ai didi

php - Laravel 5 三个模型的关系

转载 作者:行者123 更新时间:2023-11-28 23:17:25 25 4
gpt4 key购买 nike

订单表

 id   total        created_at
---+------------+--------------
2 1500.99 2017-02-02

项目表

 id   order_id    product_id   quant
---+-----------+------------+-------
66 2 5 1
67 2 6 2
68 3 5 2

产品表

 id   name        created_at
---+------------+--------------
5 PC Intel 2017-02-02
6 PC AMD 2017-02-02

模型

//Order Model
class Order extends Model{
public function items(){
return $this->hasMany('App\Item');
}
}

// Item Model
class Item extends Model{
public function producto(){
return $this->hasOne('App\Product');
}
}

// Product Model
class Product extends Model{
public function item(){
return $this->hasOne('App\Item');
}
}

我想显示关系模型的产品名称。比如我有

 $order = Order::with('items')->find($id);

但是我如何为产品的打印名称添加第三个模型?例如打印这个

$order->items->product->name //"PC Intel"

最佳答案

$order->items 返回一个集合。您无法访问属性。

相反,您必须遍历集合中的所有对象

foreach($order->items as $item) {
$item->product->name;
}

也许您应该将产品添加到您的预加载中

order = Order::with('items.producto')->find($id);

关于php - Laravel 5 三个模型的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com