This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

Codebugs
Codebugs

Hi All,

I have two database table "clients" and "attributes".
I would like to assign "attribute" to "clients" by one-to-one relationship so my "attributes" table contains a "client_id" column....but "client_id" field is nullable and I would like if the "client_id" filed is NULL then this attribute should belongs to all clients - so it would be common attribute.

What do you think about it?
What is the best practice to achieve it?

ps: I would not like to use one-to-many relationship because I would not like to assign every single common attributes to the newly created client.

Last updated

mjauvin
mjauvin

Try adding a scope to your relation definition like so (in Client model):

$hasMany = [
   'attributes' => [
      'Attribute::class',
      'scope' => 'isGlobalAttribute',
   ],
];

And add the scope to your Attribute class:

public function scopeIsGlobalAttribute($query)
{
   return $query->orWhere('client_id', null);
}

I didn't test this, but try it and give me some feedback.

Last updated

Codebugs
Codebugs

Thanks for your help, it works perfectly.

1-3 of 3

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.