gpt4 book ai didi

laravel - 如何在morphTo关系laravel中使用whereHas?

转载 作者:行者123 更新时间:2023-12-04 22:40:01 24 4
gpt4 key购买 nike

我的产品型号如下:

<?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 Eloquent 地是这样的:
$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

如果执行脚本,则存在如下错误:

Unknown column 'name'



我怎么解决这个问题?

最佳答案

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'
)
)
)

关于laravel - 如何在morphTo关系laravel中使用whereHas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49707969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com