php - How to assign a Foreign Key Value in Laravel efficiently -
so started playing laravel last night, i'm coming experience using django framework python.
so there's quite few similarities , i'm quite impressed far.
however, i'm having difficulty understanding how assign foreign key value table.
for example, have 2 models.
user order order have foreign key value user. order - has foreign key user, titled user_id
what expect able do, coming django, can authenticated user , assign directly foreign key value using this...
$order->user = auth::user(); or
$order->user_id = auth::user(); however, doesn't work... work if manually user_id so...
$order->user_id = auth::user()->id; it seems me there should exist ability laravel recognize want id of user object due foreign key definition without me having specify it... in django.
does laravel support this, , if how implemented? i'm using laravel 5.0
i'm guessing have hasmany <-> belongsto relationship between user , orders.
if so, efficient way set actual order user doing follow :
$user->orders()->associate($order); you have have orders() method in user class :
public function orders() { return $this->hasmany('path\to\your\models\order'); } for more, see : http://laravel.com/docs/5.0/eloquent#inserting-related-models
Comments
Post a Comment