Laravel 8 多态关联查询

2021-07-19 11:40 更新

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

use Illuminate\Database\Eloquent\Builder;

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

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

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

use Illuminate\Database\Eloquent\Builder;

$comments = App\Models\Comment::whereHasMorph(
    'commentable',
    ['App\Models\Post', 'App\Models\Video'],
    function (Builder $query, $type) {
        $query->where('title', 'like', 'foo%');

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

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

use Illuminate\Database\Eloquent\Builder;

$comments = App\Models\Comment::whereHasMorph('commentable', '*', function (Builder $query) {
    $query->where('title', 'like', 'foo%');
})->get(); 
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号