我已经问过this,但这在我看来并不是有效的查询方式,甚至每次查询或搜索的成本都要高得多。
function is_voted($model) {
return $model->voters->find(auth()->id());
}
function is_voted_up_or_down($model) {
$is_up = $model->voters()->where('user_id', auth()->id())->where('type', 'up')->exists();
$is_down = $model->voters()->where('user_id', auth()->id())->where('type', 'down')->exists();
if($is_up) { //$is_up has a boolean value true or false
return "up";
} elseif($is_down) { //$is_down has a boolean value true or false
return "down";
} else {
return "not voted yet";
}
}
我认为从文档中您可以清除它。 https://laravel.com/docs/11.x/eloquent-relationships
由于关系似乎是多态关系,而不是多态关系,因此只需在模型中定义函数即可雄辩地获得结果。
如果您能够将其转换为多态关系 OneToMany,那么您可以应用这样的方法
// Retrieve all posts that have at least one comment...
$posts = Post::has('comments')->get();
// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();