Saturday, 7 September 2013

Laravel: Eloquent, many to many relationship, how do I eager load only the id of related model?

Laravel: Eloquent, many to many relationship, how do I eager load only the
id of related model?

I'm using Eloquent to select a single row from a table called
"businesses". Any business can be associated with one or more
"Industries". I've set this up in the business model such that:
public function industries() {
return $this->belongsToMany('Industry');
}
In the controller I am eager loading the industries when I select the model:
$mdl = Business::find($business_id);
$mdl->load('industries');
return Response::json($mdl);
This returns something like this:
{"id":123,"name":"My Business","address":"123 Easy
Street","industries":[{"id":1,"name":"Technology"},{"id":7,"name":"Research"}]}
This is almost what I need. I'm looking to just have the response look
like this instead:
{"id":123,"name":"My Business","address":"123 Easy
Street","industries":[1,7]}
I know I could just do something like this:
$ind = array();
foreach($mdl->industries as $industry) $ind[] = $industry->id;
$mdl->industries = $ind;
I'd rather not do that though. It's ugly and it makes my code look very
non-laravel.
The reason I'd like to do it this way in the first place is because when I
SAVE the business I am going to use something like this:
$mdl->industries()->sync(Input::get('industries'));
The SYNC method only accepts an array of IDs so I'd rather the JSON object
going to and from the server have the same format. I'd really rather not
an array of objects when I load it and an array of ids when I save. Is
there a best practice for this sort of thing or an easier way to
accomplish what I'm trying to do?
Thanks!

No comments:

Post a Comment