阅读(80) (6)

Laravel 8 多态关联查询

2021-07-08 09:44:46 更新

要查询 MorphTo 关联的存在,可以使用 whereHasMorph 方法及其相应的方法:

use IlluminateDatabaseEloquentBuilder;

// 查询与帖子或视频相关并且标题包含 foo 的评论...
$comments = AppModelsComment::whereHasMorph(
    'commentable',
    ['AppModelsPost', 'AppModelsVideo'],
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get();

// 查询与帖子相关的评论,标题不包含 foo%...
$comments = AppModelsComment::whereDoesntHaveMorph(
    'commentable',
    'AppModelsPost',
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get(); 

你可以使用 $type 参数根据相关模型添加不同的约束:

use IlluminateDatabaseEloquentBuilder;

$comments = AppModelsComment::whereHasMorph(
    'commentable',
    ['AppModelsPost', 'AppModelsVideo'],
    function (Builder $query, $type) {
        $query->where('title', 'like', 'foo%');

        if ($type === 'AppModelsPost') {
            $query->orWhere('content', 'like', 'foo%');
        }
    }
)->get(); 

您可以提供 * 作为通配符,让 Laravel 从数据库中查询所有可能的多态类型,而不是传递可能的多态模型数组。Laravel 将执行其他查询以执行此操作:

use IlluminateDatabaseEloquentBuilder;

$comments = AppModelsComment::whereHasMorph('commentable', '*', function (Builder $query) {
    $query->where('title', 'like', 'foo%');
})->get();