简体   繁体   中英

Laravel belongsTo returning null when using 'with'

I'm just getting started with Laravel so please forgive any noobness.

I have a User and Order model, a user has many orders:

# Inside User model
public function orders()
{
    $this->hasMany('Order');
} 

# Inside Order
public function user()
{
    return $this->belongsTo('User');
}

// Not sure if this is upsetting anything (also in Order)
public function products()
{
    return $this->belongsToMany('Product');
}

So I think I have the above right.

But when I do this:

 $users = User::with('orders')->find(1);
 return $users;

I get Call to a member function addEagerConstraints() on null .

However, if I do it the other way around, it works great:

$orders = Order::with('User')->get();
return $orders;

What am I doing wrong / what don't I understand?! Or is my problem bigger than I think?

Database:

在此处输入图片说明

The problem is you don't have return for your orders relationship. It should be:

public function orders(){
    return $this->hasMany('Order');
} 

You should also use your relationships case sensitive. you showed:

$orders = Order::with('User')->get();

is working, but you should rather use

$orders = Order::with('user')->get();

to avoid extra queries to your database in future

For anyone else that runs across this, I was having the same issue, but my problem was that I had the foreign/local keys swapped. Example:

// This is correct for hasX relationships
public function user() {
    return $this->hasOne('App\Models\User', 'user_id', 'local_key_user_id');
}

// This is correct for belongsTo relationships
public function user() {
    return $this->belongsTo('App\Models\User', 'local_key_user_id', 'user_id');
}

Notice that for hasX relationships, the foreign key is the second parameter, and the local key is the third. However, for belongsTo relationships, these two are swapped.

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