Nur Uddin
Nur Uddin

Reputation: 2948

Conditional Relationship in laravel Eloquent

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.
}

Upvotes: 2

Views: 4542

Answers (1)

Alfonso Sánchez
Alfonso Sánchez

Reputation: 41

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.

Upvotes: 2

Related Questions