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');
}
}
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();