Laravel Eloquent with() - >返回null

Jaz*_*zzy 9 php mysql orm laravel eloquent

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

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

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

//产品型号

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

//品牌模型

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

The*_*pha 13

你有这个:

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

你得到nullbrand,它可能是因为你有一些特定的字段,很可能你没有foreing_keyproducts创建关系的表中选择Brand,所以如果你的products表包含foreign_key(可能brand_id)brand表,那么你必须foreign_key从该products表也.所以,只需foreign_key/brand_id$fields变量中添加它即可.如果没有关系构建器key(FK),Brand则不会加载.

  • 只是为了在这里解决这个问题 - 如果您使用“with”语句指定任何列,则需要确保包含“id”列,否则您将再次获得 null。我假设“id”需要与外键匹配 - 但这是我假设“with”语句本身所做的事情。 (2认同)