简体   繁体   中英

Laravel Eloquent Inaccessible by $model->id;

I've done this many times before but somehow my mind is stuck on this one:

$data['conversations'] = Conversation::with("sender")->received()->get();

Doing {{ $conversation }} produces:

{
    "id": "1",
    "subject": "",
    "sender": {
        "id": "4",
        "email": "jane@doe.com",
        "name": "Jane Poe",
        "group_id": "3",
        "created_at": "2014-12-22 20:31:00",
        "updated_at": "2014-12-22 20:31:00"
    },
    "receiver": "1",
    "created_at": "2015-01-04 00:00:00",
    "updated_at": "2015-01-04 00:00:00"
}

Notice that "sender? Now {{ $conversation->sender->email }} gives:

Trying to get property of non-object

When calling {{ $conversation->sender }} it prints "4" only (the id).

sender is stored in conversation table in a column named sender .

$conversation->sender() didn't work either

This is the code:

class Conversation extends Eloquent {

    protected $table = 'conversations';

    public function sender()
    {
        return $this->belongsTo('User','sender','id');
    }

    public function receiver()
    {
        return $this->belongsTo('User','receiver','id');
    }

}

The relation can't have the same name as the foreign key (or basically any column)

Just change sender to sender_id . Then you can even remove it from the relationship declaration since it's the conventional naming.

public function sender()
{
    return $this->belongsTo('User');
}

(And because id is probably the primary key of User you can remove that as well)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM