For some reason, I can't figure out how to retrieve what I want from my database using Eloquent. I have a User model and an Organization model, each connected by a belongsToMany relationship. The pivot table user_orgs that connects them has an additional column, indicating if the organization is the "primary" organization (is_primary) for the user.
Every time I query users, including the logged in user, I would like their primary organization name and ID to be accessible via attributes.
//User Model
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
//...
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function organizations()
{
return $this->belongsToMany(Organization::class, 'user_orgs', 'user_id', 'organization_id')->withTimestamps()->withPivot('is_primary');
}
//...
//Organization Model
class Organization extends Model
{
//...
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function members()
{
return $this->belongsToMany(User::class, 'user_orgs', 'organization_id', 'user_id')
->withTimestamps();
}
//...
My first thought was global scoping, which fails due to the following error:
//User Model
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
//...
public static function boot()
{
parent::boot();
static::addGlobalScope('primaryOrg', function (Builder $builder) {
$builder->join('user_orgs', 'users.id', '=', 'user_orgs.user_id')
->join('organizations', 'organizations.id', '=', 'user_orgs.organization_id')
->where('user_orgs.is_primary', '=', 1);
});
}
//...
Error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `users` inner join `user_orgs` on `users`.`id` = `user_orgs`.`user_id` inner join `organizations` on `organizations`.`id` = `user_orgs`.`organization_id` where `id` = 100 and `user_orgs`.`is_primary` = 1 limit 1)