How To Define Querying Relations With Laravel Framework

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 Relations in Laravel

How To Define Querying Relations With Laravel Framework

Querying Relations

Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing the relationship queries. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.

For example, imagine a blog system in which a Video model has many associated Comments models:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    public function Comments()
    {
        return $this->hasMany('App\Comments');
    }
}


You may query the Comments relationship and add additional constraints to the relationship like so:
$Video = App\Video::find(1);

$Video->Comments()->where('active', 1)->get();


You are able to use any of the query builder methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you.

Chaining orWhere Clauses After Relationships

As demonstrated in the example above, you are free to add additional constraints to relationships when querying them. However, use caution when chaining orWhere clauses onto a relationship, as the orWhere clauses will be logically grouped at the same level as the relationship constraint:
 

$Video->Comments()
    ->where('active', 1)
    ->orWhere('votes', '>=', 100)
    ->get();


In most situations, you likely intend to use constraint groups to logically group the conditional checks between parentheses:

use Illuminate\Database\Eloquent\Builder;

$Video->Comments()
    ->where(function (Builder $query) {
        return $query->where('active', 1)
            ->orWhere('votes', '>=', 100);
    })
    ->get();

Related Post