Hi guys,
I'm trying to find the best way to implement the following.
I have a Client of a given Sector who belongs to an Agency.
clients table:
client_id
sector_id NOT NULL
agency_id NOT NULL
[...]
Both sector_id and agency_id are mandatory and this rule is enforced in DB (NOT NULL fields, although).
I'd also like my Client model to ensure agency_id and sector_id are set so I coded it like so:
// BaseModel declares an event handler on "saving"
// and uses Validator with $rules to check input
class Client extends BaseModel
{
protected $table = 'clients';
protected $primaryKey = "client_id";
protected $guarded = ['client_id', 'agency_id', 'sector_id'];
protected static $rules = array(
'name' => 'required|max:255',
[other rules on contact info etc]
);
public function agency()
{
return $this->belongsTo('Agency');
}
public function sector()
{
return $this->belongsTo('Sector');
}
}
And in my unit test I go
$sector = Sector::find(1);
$agency = Agency::find(1);
$new_client = new Client($attributes); // $attributes contains fields such as name, contact info etc
$new_client->sector()->associate($sector);
$new_client->agency()->associate($agency);
$s = $new_client->save();
Is this the right way to do it? Do I have to call associate method twice to link a Client to both Sector and Agency?
Thanks!
Yes, that's the way for the relation linking, but what is that you want to test there?
Hey,
above test is only there to make sure things work.
I wanted to have another test which would fail if a client had no sector associated to it and I was wondering if guarding required fields was the way to go.
Thanks for your answer.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community