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

我有UserOrder型号,用户有很多订单:

# 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');
}

所以我认为我有以上的权利.

But when I do this:

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

我得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?

数据库:

在此处输入图像描述

推荐答案

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

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

您还应该使用区分大小写的关系.您展示了:

$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

Laravel相关问答推荐

如何更改LIVE上的Filament占位符内容?

Nginx上带有SSL的Laravel混响

为什么Laravel在API请求时返回BadMethodCallException?

当未通过验证的字段是值数组时,Laravel$validator->;validator()方法不会引发异常

Laravel init 查询多种用途

如何在 Laravel 5 中添加我自己的自定义类?

Laravel 5.3:语法错误或访问冲突:1463 HAVING 子句中使用了非分组字段距离

我在哪里放置事件侦听器和处理程序?

Lumen 中的自定义 404 页面

Laravel 表 * 没有名为 * 的列

Laravel 监听器监听多个事件

致命错误:找不到类App\Http\Controllers\Redirect

laravel 中的 Http Post 使用 fetch api 给出 TokenMismatchException

Laravel excel maatwebsite 3.1 导入,excel 单元格中的日期列返回为未知格式数字.如何解决这个问题?

使用数据库用户提供程序时如何在 Laravel 中创建密码重置方法

使用 laravel eloquent 关系检索除 NULL 之外的所有记录

调用未定义的方法 Maatwebsite\Excel\Excel::load()

我如何从给定的日期时间 struct 创建Carbon 对象?

在 Laravel 中将 Eloquent 导出到 Excel 时如何包含列标题?

Distinct values with pluck