V
V
Vanik Khachatryan2018-02-21 15:07:19
Laravel
Vanik Khachatryan, 2018-02-21 15:07:19

Why doesn't Laravel see a simple model relationship?

Feedback model:

class Reviews extends Model
{
    protected $timestamp = false;

    public function user() {
        return $this->hasOne('Users', 'id', 'user');
    }
}

Table Reviews:
5a8d60b8c4cb7407532001.png
An Attempt to Withdraw
@foreach($reviews as $review)
            <div class="card">
                {{$review->user->firstName}}
                {{$review->text}}
            </div>
        @endforeach

Mistake:
5a8d610a6450b394418445.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Antonio Solo, 2018-02-21
@solotony

name everything correctly
The model should be called not Reviews but Review
user is this property Reviews ? Is it the id from the users table? then you need to call user_id
then it would be

public function user() {
        return $this->hasOne('App\User', 'id', 'user_id');
    }

although this is not true
. Since the Review model contains a foreign key on User, it should be
public function user() {
        return $this->belongsTo('App\User', 'user_id', 'id');
}

H
hakkol, 2018-02-21
@hakkol

Well, from the error it is clear that your connection is not working, set the correct path to the model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question