is Accreditation a model representing the pivot table?
Jul 19, 2017
4
Level 13
Get pivot data from another model as query scope.
Hi everyone,
I'm struggling with a bit of an odd query. my models are as follows:
class Register extends Model
{
public function users()
{
return $this->belongsToMany(User::class)
->withPivot([
'credit',
]);
}
}
class User extends Model
{
public function registers()
{
return $this->belongsToMany(Register::class)
->withPivot([
'credit',
]);
}
}
class Accreditation extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function register()
{
return $this->belongsTo(Register::class);
}
}
So i can access both ids from the Accreditation model.
I'm trying to make a query scope where only records with credit = 1 will show up. So far i managed to get it to work by making an extra method and filtering by that with Collections, but i'd really like to chain this with other query methods.
I would appreciate any suggestions.
Level 13
Ok i figured it out. Here's the solution i found:
I added these relations
class User
{
public function registers_with_credit()
{
return $this->belongsToMany(Register::class)
->withPivot('credit')
->withTimestamps();
->wherePivot('credit', 1);
}
class Register
{
public function users_with_credit()
{
return $this->belongsToMany(User::class)
->withPivot('credit')
->withTimestamps();
->wherePivot('credit', 1);
}
And then the query scope:
class Accreditation
{
public function scopeWithCredit($query)
{
return $query
->has('user.registers_with_credit')
->has('register.users_with_credit');
}
It's weird and very specific but maybe this will save someone a headache at some point.
Please or to participate in this conversation.