I want to create (on Laravel 5.2) a pivot between two entities, let's assume that we have the entities User and Phone. In our world, a user can have several phones, and te phones can have several owners.
For a reason, I must target the user's phone by it's serial number and the build year (let's assume that serials can't be identical on a same year).
So I have my tables users
, phones
andusers_phones
.
===== Table users =====
id
username
...
===== Table phones ====
id
serial_numer
build_year
===== Table users_phones ====
user_id
phone_serial
phone_build_year
I have my relation on my model Phone :
public function users()
{
return $this->belongsToMany(
User::class,
'users_phones',
'user_id',
'phone_serial'
)->withPivot('phone_build_year');
}
When I wan't to add some entries like that :
$phone->users()->attach([$user->id => [
'phone_build_year' => $phone->build_year
]]);
The SQL request generated is the following one :
insert into `users_phones` (`user_id`, `phone_serial`, `phone_build_year`) values (1, 5, 2016)
My problem is that the 5
in the sql request is the phone id and not its serial. I didn't find how to precise to Laravel to use the field we chose (here the serial) rather than the id.
Is it possible to do that, or am I condemned to create a model to manipulate my special pivot table ? I admit that I would appreciate if I could avoid that way.
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Twe5D6
via IFTTT
Aucun commentaire:
Enregistrer un commentaire