Laravel Eloquent with()-> 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24130410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:37:23  来源:igfitidea点击:

Laravel Eloquent with()-> returning null

phpmysqlormlaraveleloquent

提问by Jazzy

I am trying to use Eloquent to get a specific product that has a brand_idcolumn that maps to a brandstable, the brandarray is coming back empty.

我正在尝试使用 Eloquent 来获取具有brand_id映射到brands表的列的特定产品,该brand数组返回空。

Is there anything obvious here that needs to be changed?

这里有什么明显的需要改变的吗?

$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);

//Product model

//产品型号

class Product extends Eloquent {
    ...
    public function brand()
    {
        return $this->belongsTo('Brand');
    }

//Brand model

//品牌型号

class Brand extends Eloquent {
...
public function products()
{
    return $this->hasMany('Product');
}

回答by The Alpha

You have this:

你有这个:

$product = Product::with('images', 'brand')
                  ->select($fields)
                  ->where('display', 1)
                  ->find($id);

You are getting nullfor brandand it could be because you have some specific fields and most probably you didn't select the foreing_keyfrom the productstable that creates the relationship with Brand, so if your productstable contains the foreign_key(probably brand_id) of brandtable then you have to select that foreign_keyfrom the productstable too. So, just add that foreign_key/brand_idin the $fieldsvariable. Without the relation builder key (FK) the Brandwon't be loaded.

你得到nullbrand,它可能是因为你有一些特定的领域和最可能是你没有选择foreing_keyproducts创建与关系表Brand,因此,如果您的products表包含的foreign_key(可能brand_id)的brand表,那么你必须选择foreign_key从该products表也。所以,只要添加foreign_key/brand_id$fields变量。没有关系构建器键 ( FK)Brand将不会被加载。