[英]Laravel Eloquent with()-> returning null
我正在嘗試使用Eloquent來獲得具有brand_id
列的特定產品,該列映射到brands
表, brand
陣列將變回空白。
這里有什么明顯的東西需要改變嗎?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
//產品型號
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
//品牌模型
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
你有這個:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
你的brand
是null
,可能是因為你有一些特定的字段,很可能你沒有從products
表中選擇foreing_key
來創建與Brand
的關系,所以如果你的products
表包含foreign_key
(可能是brand_id
) brand
表然后你必須從products
表中選擇foreign_key
。 所以,只需在$fields
變量中添加foreign_key/brand_id
。 如果沒有關系構建器密鑰( FK
),則不會加載Brand
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.