Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

like image 298
Djave Avatar asked Nov 06 '14 11:11

Djave


2 Answers

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

like image 73
Marcin Nabiałek Avatar answered Oct 20 '22 09:10

Marcin Nabiałek


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.

like image 28
garrettmills Avatar answered Oct 20 '22 10:10

garrettmills