What Is Querying Polymorphic Relationships In Laravel

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.today we are going to discuss about Querying Polymorphic Relationships In Laravel

What Is Querying Polymorphic Relationships In Laravel

Querying Polymorphic Relationships

To query the existence of MorphTo relationships, you may use the whereHasMorph method and its corresponding methods:

What is MorphTo method?
"MorphTo" is used to define the relationship from a one-to-one or one-to-many polymorphic table to whichever model or models .

What is whereHasMorph() method?
new whereHasMorph() used to combing through one result after another.

use Illuminate\Database\Eloquent\Builder;

// Retrieve comments associated to posts or videos with a title like foo%...

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

// Retrieve comments associated to posts with a title not like foo%...

$comments = App\Comment::whereDoesntHaveMorph(
    'commentable',
    'App\Post',
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get();


You may use the $type parameter to add different constraints depending on the related model:

use Illuminate\Database\Eloquent\Builder;

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

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


Instead of passing an array of possible polymorphic models, you may provide * as a wildcard and let Laravel retrieve all the possible polymorphic types from the database. Laravel will execute an additional query in order to perform this operation:
 

use Illuminate\Database\Eloquent\Builder;

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

Related Post