Mohamed Athif Mohamed Athif - 1 year ago 49
PHP Question

Set relations on two fields related to the same table

I have a

table with many users, for example:

id | name
1 | mike
2 | nina
3 | john

I also have a
table with a
that represents the original creator of the post and a
that is filled if the post was locked by an editor.

Any user can lock or open the post but if the post is locked only that user can edit it. This are my relations:

User model:

public function posts(){
return $this->hasMany('App\Post');

Post model:

public function user(){
return $this->belongsTo('App\User');

And I can retrieve the author easily by


I would like to be able to get both the original creator user and the editor. For instance, a sample of the post table:

| id | user_id | post | locked_user_id |
| 1 | 1 | blah blah | 2 |

In this case
returns mike but I want to be able to get the user nina which is currently locking the post.

How can I accomplish this?

Answer Source

Assuming locked_user_id can be null, and, if so, the returned user is based on the used_id, you could update the user() relation on the Post model to:

public function user()
    if (!is_null($this->locked_user_id)) {
        return $this->belongsTo('App\User', 'locked_user_id', 'id');

    return $this->belongsTo('App\User');

So, if there's a locked_user_id the returned used is based on this field, otherwise the returned user is based on the user_id field

As per the comment, if you want to access both users, you can add another relation on the Post model. For instance

// Assuming `user_id` is not nullable, this will always return the original user
public function creator()
    return $this->belongsTo('App\User');

// Assuming `locked_user_id` is nullable, this will return either `null`, if there is no editor or the user that locked the post
public function editor()
    return $this->belongsTo('App\User', 'locked_user_id', 'id');

On your code you can do something like:

if (is_null($this->editor)) {
    dd('There is no editor');
} elseif ($this->editor->id === $this->creator->id) {
    dd('The original creator has locked the post');
} else {
    dd('The post was created by ' . $this->creator->name. ' but now is locked by ' . $this->editor->name);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download