Laravel雄辩with()->返回null [英] Laravel Eloquent with()-> returning null

查看:65
本文介绍了Laravel雄辩with()->返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Eloquent来获取具有映射到brands表的brand_id列的特定产品,而brand数组又变空了.

I am trying to use Eloquent to get a specific product that has a brand_id column that maps to a brands table, the brand array is coming back empty.

这里是否有明显的需要更改的地方?

Is there anything obvious here that needs to be changed?

$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表包含brand表的foreign_key(可能是brand_id),那么您也必须从products表中选择该foreign_key.因此,只需在$fields变量中添加该foreign_key/brand_id.没有关系生成器键(FK),将不会加载Brand.

You are getting null for brand and it could be because you have some specific fields and most probably you didn't select the foreing_key from the products table that creates the relationship with Brand, so if your products table contains the foreign_key (probably brand_id) of brand table then you have to select that foreign_key from the products table too. So, just add that foreign_key/brand_id in the $fields variable. Without the relation builder key (FK) the Brand won't be loaded.

这篇关于Laravel雄辩with()->返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆