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.
}
5
  • 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. Commented Sep 21, 2014 at 7: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. Commented Sep 21, 2014 at 7: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. Commented Sep 21, 2014 at 7:42
  • 2
    You can use laravel.com/docs/eloquent#polymorphic-relations for this, just alter poster_type to User / Admin and make sure you have those 2 Eloquent models. Commented Sep 21, 2014 at 8:26
  • 2
    stackoverflow.com/questions/43668153/… Please check this link for solution Commented Sep 18, 2017 at 6:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.