Reputation: 253
I have 3 tables that have relations
Budgets Table :
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
user_id | bigint(20) unsigned | NO | MUL | NULL | |
purpose | varchar(255) | NO | NULL | ||
delivery_plan | varchar(255) | NO | NULL | ||
status | varchar(255) | NO | NULL | ||
created_at | timestamp | YES | NULL | ||
updated_at | timestamp | YES | NULL |
Periods table :
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
name | varchar(255) | NO | NULL | ||
term_id | bigint(20) unsigned | NO | NULL | ||
created_at | timestamp | YES | NULL | ||
updated_at | timestamp | YES | NULL |
Terms table :
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
name | tinyint(4) | NO | NULL | ||
status | varchar(255) | NO | NULL | ||
created_at | timestamp | YES | NULL | ||
updated_at | timestamp | YES | NULL |
Budget Model :
public function period()
{
return $this->belongsTo(Period::class, 'delivery_plan', 'name');
}
Period Model :
public function budgets()
{
return $this->hasMany(Budget::class, 'delivery_plan', 'name');
}
public function term()
{
return $this->belongsTo(Term::class);
}
Term Model :
public function periods()
{
return $this->hasMany(Period::class);
}
So each budget belongsTo one period, and period belongs to one term. Then i'd like to query Budgets based on term's name. So how to query it with laravel eager loading ?
Upvotes: 2
Views: 1589
Reputation: 652
Simply you can use hasManyThrough. So, you can link between the Budget
and Term
via Period
Upvotes: -1
Reputation: 2462
you use whereHas method :
$builder->whereHas('relationName', function (Builder $builder){ /* your query */ });
if you don't have any condition to apply, you can just use whereHas without the callback
you can chain multiple whereHas if you need to
Budget::whereHas("period", function(Builder $builder) {
$builder->whereHas('term', function(Builder $builder) {
$builder->where('name', '=', 'test');
})
})
you can even simplify that by using dot notation
Budget::whereHas("period.term", function(Builder $builder) {
$builder->where('name', '=', 'test');
})
Upvotes: 3