【问题标题】:Laravel Eloquent with()-> returning nullLaravel Eloquent with()-> 返回 null
【发布时间】:2014-07-30 14:11:39
【问题描述】:

我正在尝试使用 Eloquent 获取具有映射到 brands 表的 brand_id 列的特定产品,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');
}

【问题讨论】:

  • 你检查过:$brand = $product->brand(); ?
  • $fields 变量中有哪些字段?

标签: php mysql orm laravel eloquent


【解决方案1】:

你有这个:

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

你得到null for brand,这可能是因为你有一些特定的字段,很可能你没有从products表中选择foreing_keyBrand建立关系,因此,如果您的products 表包含brand 表的foreign_key(可能是brand_id),那么您也必须从products 表中选择foreign_key。因此,只需将 foreign_key/brand_id 添加到 $fields 变量中即可。如果没有关系构建器密钥 (FK),Brand 将不会被加载。

【讨论】:

  • 天才。谢谢,您对 $fields 的看法完全正确。
  • 只是在此处添加此内容-如果您使用“with”语句指定任何列,则需要确保包含“id”列,否则您将得到再次为空。我假设需要“id”来匹配外键 - 但这是我假设“with”语句自己完成的事情。
猜你喜欢
  • 2017-04-01
  • 2013-02-25
  • 2016-04-27
  • 1970-01-01
  • 2019-06-22
  • 2020-02-18
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
相关资源
最近更新 更多