Answer the question
In order to leave comments, you need to log in
How valid is a condition on a relation in laravel?
Good afternoon,
There are 2 models - User and Contract( provider_id, customer_id, sign )
class User extends Model {
public function isProvider()
{
return $this->role === 1;
}
public function isCustomer()
{
return $this->role === 2;
}
public function contracts()
{
if($this->isProvider())
return $this->hasMany(Contract::class, 'provider_id');
if($this->isCustomer())
return $this->hasMany(Contract::class, 'customer_id');
}
}
Answer the question
In order to leave comments, you need to log in
Laravel does not care deeply, this is business logic. The problem can only be in the opposite direction if the user is tied to the contract:
// что за юзер — провайдер или потребитель?
// по какому полю строить связь?
$contract->user()->associate($user);
However, apparently, it is enough to make a similar construction with conditions on the other side. But there may be problems: they created an instance of the model, provider_id
and customer_id
did not fill it in - what to check in the conditions?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question