To represent the relationships between the Agent and Agency entities using Eloquent's DB contracts, you can define the relationships in the respective models.
In the Agent model, you can define the "owns" relationship with the Agency model using the hasOne method. This relationship indicates that an agent can own only one agency.
class Agent extends Model
{
public function agency()
{
return $this->hasOne(Agency::class, 'owner_id');
}
}
In the Agency model, you can define the "works for" relationship with the Agent model using the belongsToMany method. This relationship indicates that an agency can have multiple agents working for it.
class Agency extends Model
{
public function agents()
{
return $this->belongsToMany(Agent::class, 'agency_agent');
}
}
To differentiate between the two relationships, you can use custom names for the relationships. For example, you can name the "owns" relationship as "ownedAgency" and the "works for" relationship as "workingAgents".
class Agent extends Model
{
public function ownedAgency()
{
return $this->hasOne(Agency::class, 'owner_id');
}
public function workingAgents()
{
return $this->belongsToMany(Agent::class, 'agency_agent');
}
}
This way, you can access the relationships using the custom names:
$agent = Agent::find(1);
// Get the owned agency
$ownedAgency = $agent->ownedAgency;
// Get the agents working for the agency
$workingAgents = $ownedAgency->workingAgents;
Note: Make sure to adjust the foreign key and pivot table names according to your database schema.