【问题标题】:Laravel5.8 belongsTo relation not working for foreach loopLaravel5.8 belongsTo 关系不适用于 foreach 循环
【发布时间】:2023-03-26 21:06:01
【问题描述】:

我正在使用 hasMany 和 belongsTo 处理 Laravel 关系。它适用于 hasMany 关系,但我在 belongsTo 上遇到问题,用于收集 foreach 循环。这是我的categories 表。

    id    name
  --------------
    1     food

还有products 表。

    id    name         category_id
  ----------------------------------
    1     pizza          1
    2     hamburger      1

下面是hasMany产品型号。

# Product.php

public function products()
{
    return $this->hasMany(Product::class);
}

下面是belongsTo类别模型。

# Category.php

public function category()
{
    return $this->belongsTo(Category::class, 'id');
}

我在刀片中遇到错误:

试图获取非对象的属性

 <tbody>
   @foreach ($products as $product)
      <tr>
           <td> {{ $product->category->name }} </td>
       </tr>
    @endforeach
  </tbody>

任何关于这方面的建议或指导将不胜感激,谢谢

【问题讨论】:

    标签: php laravel laravel-5 relationship belongs-to


    【解决方案1】:

    问题在于方法定义。 belongsTo 方法的第二个参数是外键列名。试试这个:

    # Product.php
    
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }
    

    但是,鉴于您的外键是模型名称后跟 _id (category_id),Laravel 默认会查找此键.. 所以您可以像这样简化它:

    # Product.php
    
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
    

    来自documentation

    ...在上面的示例中,Eloquent 将尝试匹配 post_idComment 模型到id 上的Post 模型。雄辩 通过检查名称来确定默认外键名称 关系方法并在方法名称后面加上_ 通过主键列的名称。但是,如果外键在 Comment 模型不是 post_id,您可以传递自定义键名 作为belongsTo 方法的第二个参数:

    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post', 'foreign_key');
    }
    

    【讨论】:

    • @joenpcnpcsolution 很高兴为您提供帮助。您现在可以接受答案了。
    【解决方案2】:

    Category.php

    public function category()
    {
      return $this->belongsTo(Category::class, 'category_id');
    }
    

    而不是 category() 中的 'id' 使用 'category_id'..... 因为您已将 category_id 作为外键......所以 laravel 将搜索它......

    【讨论】:

    • 亲爱的 Varsha Jadhav,谢谢。
    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多