【问题标题】:Laravel - Query builder get relationLaravel - 查询构建器获取关系
【发布时间】:2018-03-20 08:29:32
【问题描述】:

在我的项目中,我有一个多态关系。这种关系如下:

Plugins
    id - integer
    composer_package - string

Themes
    id - integer
    composer_package - string

Products
    id - integer
    name - text
    ...
    commentable_id - integer
    commentable_type - string

当我需要显示属于主题的所有产品时,我会执行以下操作:

$themes = DB::table('products')->orderBy('id', 'asc')->where('productable_type', Theme::class)->get();

上面的代码为我提供了productable_type 字段填充有App/Theme 的所有产品的列表,我使用像@foreach($themes as $theme) 这样的foreach 循环显示它们。现在我的问题是。 我需要从属于该产品的主题表中获取composer_package。所以比如说。我从产品表中得到一个产品,其中productable_id 为3。我想要主题表中ID 为3 的composer_package 字段的值。当我执行{{ $theme->products->composer_package }} 或{{ $theme->composer_package }} 时,它给了我错误Undefined property这是什么原因?

这是我的产品模型

public function product()
{
    return $this->morphTo();
}


public function order_items()
{
    return $this->hasMany(Orderitems::class);
}

这是我的主题模型

public function webshops()
{
    return $this->hasMany(Webshop::class);
}


public function products()
{
   return $this->morphMany(Product::class, 'productable');
}

提前致谢!

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您是否有任何理由使用DB 外观而不是实际模型来提取数据?

    您遇到的一个问题是您的多态关系存储在 commentable_id / commentable_type 字段中,而您的函数名称是 product。 Laravel 仅通过命名就可以发挥一些神奇的作用,所以让我们确保列名和多态函数名在产品模型中匹配:

    public function commentable()
    {
        return $this->morphTo();
    }
    

    之后,在控制器中尝试这样的操作:

    $themeProducts = Product::where('commentable_type', Theme::class)->get();
    

    这个在视图中

    @foreach ($themeProducts as $themeProduct)
        {{ $themeProduct->commentable->composer_package }}
    @endforeach
    

    【讨论】:

      【解决方案2】:

      您的表具有“可评论”,但您的模型正在寻找“可生产”。您还缺少一种方法。

      在您的产品模型中添加:

      public function commentable(){
          return $this->morphTo();
      }
      

      在您的 主题 模型中,将 products() 方法修改为:

      public function products(){
         return $this->morphMany(Product::class, 'commentable');
      }
      

      您还可以将表中的commentable_type 和commentable_id 列更新为productable_type 和productable_id,在这种情况下,您需要将上述产品型号代码中的commentable() 重命名为productable() , 和 'commentable' 到 'productable' 在上述主题模型的代码中。

      (来源:https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations)

      【讨论】:

        【解决方案3】:

        如上述答案中所述与模型创建关系,然后您可以使用 with helper 检索关系。 例如。: Product::where('commentable_type', Theme::class)->with('commentable')->get();

        然后就可以像上面说的那样直接使用了。 例如:$themeProduct->commentable

        【讨论】:

          猜你喜欢
          • 2021-12-30
          • 1970-01-01
          • 2017-03-30
          • 2019-12-09
          • 2013-05-02
          • 1970-01-01
          • 2016-01-31
          • 2021-08-31
          • 2019-04-24
          相关资源
          最近更新 更多