I'm kinda newbie dealing with laravel, and I got stuck into something
I have this scenario and I'm strugling to get the correct relationship for that, and I hope someone could show me some enlighting thoughts :)
I've these two models: Order and User. I have two types of users. Clients and professionals. When a client places an order, it is assigned to 5 professionals.
I created a pivot table 'order_user', to deal with the selected professionals for each order.
Oh, I can't split users into clients and professionals, because a professional can also act as a client, and order services from other types of professionals.
These are the pieces of relationship code I thought I would be adding to the two models (probably not working at all)
on my User model:
The client user orders
public function orders(){
return $this->hasMany('App\Orders');
}
The professional user assigned orders
public function assigned_orders(){
return $this->belongsToMany('App\Order', 'order_user', 'order_id', 'user_id');
}
on my Order model:
The order creator user
public function user(){
return $this->belongsTo('App\User');
}
The users assigned to that order
public function assigned_users(){
return $this->belongsToMany('App\User', 'order_user', 'order_id', 'user_id');
}
Does this make any sense?
How could I, as a professional, retrieve, the orders which I'm assigned to?
And if there's other points to change, let me know
Thank u all in advace!
I think you can simplify your setup some --
In your User model:
public function orders(){
return $this->belongsToMany('App\Order', 'order_user', 'order_id', 'user_id');
}
In your Order model:
public function users(){
return $this->belongsToMany('App\User', 'order_user', 'order_id', 'user_id');
}
Then all you need to do to retrieve "your" assigned Orders is:
$my_orders = User::find(Auth::user()->id)->orders;
And if you want to keep the "owner" concept, in your Order model:
public function owner(){
// references owner_id
return $this->belongsTo('App\User');
}