【问题标题】:How can I use whereHas in the morphTo relation laravel?如何在 morphTo 关系 laravel 中使用 whereHas?
【发布时间】:2018-09-17 09:04:10
【问题描述】:

我的产品型号是这样的:

<?php
...
class Product extends Model
{
    ...
    protected  $fillable = ['name','photo','description',...];
    public function favorites(){
        return $this->morphMany(Favorite::class, 'favoritable');
    }
}

我最喜欢的模特是这样的:

<?php
...
class Favorite extends Model
{
    ...
    protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
    public function favoritable()
    {
        return $this->morphTo();
    }
}

我的 laravel 雄辩是这样的:

$q = $param['q'];

$query = Favorite->where('user_id', auth()->user()->id)
                 ->with('favoritable');

if($q) {
    $query->whereHas('favoritable', function ($query) use ($q) {
        $query->where('name', 'like', "%$q%");
    });
}

$query = $query->paginate(5);

return $query

如果脚本执行了,就会出现这样的错误:

未知列“名称”

我该如何解决这个问题?

【问题讨论】:

标签: laravel laravel-5 polymorphism laravel-eloquent laravel-5.6


【解决方案1】:

Laravel 5.8 包含用于查询多态关系的新功能。

whereHasMorph() 使查询多态关系成为可能,如下所示:

Comment::whereHasMorph('commentable', [Post::class, Video::class], function($query){
    $query->where('title', 'foo');
})->get();

这会产生以下查询:

select * from "comments"
where (
  (
    "commentable_type" = 'App\Post' and exists (
      select * from "posts" 
      where "comments"."commentable_id" = "posts"."id" and "title" = 'foo'
    )
  ) or (
    "commentable_type" = 'App\Video' and exists (
      select * from "videos" 
      where "comments"."commentable_id" = "videos"."id" and "title" = 'foo'
    )
  )
)

【讨论】:

  • 太棒了❤️️
【解决方案2】:

已解决

我添加了这个方法:

public function product()
{
    return $this->belongsTo(Product::class, 'favoritable_id')
        ->where('favorites.favoritable_type', Product::class);
}

在最喜欢的模型中

我把 laravel eloquent 改成这样:

$query->whereHas('product', function ($query) use ($q) {
    $query->where('name', 'like', "%$q%");
});

有效

【讨论】:

  • 感谢您抽出宝贵时间回来分享解决方案。
  • 我尝试使用文档建议应该工作的 whereHasMorph,但我收到错误“非静态方法 Illuminate\Database\Eloquent\Builder::whereHasMorph() 不应静态调用” - 此解决方案不过似乎效果很好!
猜你喜欢
  • 1970-01-01
  • 2014-12-01
  • 2017-09-22
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 2018-06-19
  • 2014-01-11
相关资源
最近更新 更多