2

Let I have 3 table named user, admin, post

My post table structure is

-id
-poster_id
-poster_type //if value is 1 then poster_id will be releted with user table. if value is 2 then poster_id releted with admin table.

Now How writte belongsTo relationship with two table based on poster_type value

I want to do in Post model like this

public function Author(){
     return $this->belongsTo('User', 'poster_id')->where('poster_type', '1') //poster_type is the field of post table.
}
Nur Uddin
  • 2,778
  • 6
  • 16
  • 22
  • You should probably rethink your database design and use the users table for both users and admins, with a boolean column that determines if the user is an admin or not. –  Sep 21 '14 at 07:05
  • Admin is also a user. So, it does not make sense to create separate table for admin and user for all other users. Either you create each table for each user group or place a column named 'group' or 'type' in users table to distinct user group. – user4055288 Sep 21 '14 at 07:09
  • Actually this is not my database. I just want to get Idea how I relate a table based on a value. ex: if value is 1 then I want relate with table `x` if value is 2 then I want relate with table `y`. – Nur Uddin Sep 21 '14 at 07:42
  • 2
    You can use http://laravel.com/docs/eloquent#polymorphic-relations for this, just alter `poster_type` to `User` / `Admin` and make sure you have those 2 Eloquent models. – Jarek Tkaczyk Sep 21 '14 at 08:26
  • 2
    https://stackoverflow.com/questions/43668153/how-to-setup-conditional-relationship-on-eloquent Please check this link for solution – abhi singh Sep 18 '17 at 06:11

1 Answers1

2

First of all, you are talking about a Polymorphic relationship, supported by eloquent. You should take a look at the documentation.

http://laravel.com/docs/eloquent#polymorphic-relations

Second, you are mixing Eloquent relationships with special data recovery functions, and that's something you should avoid. I suggest you split the relationship itself from the data recovery function.

Also, if you want to go one step further, keep the relationship in the model, and split the data recovery functions into a repository object.