Laravel 5 - 使用关系时未定义 属性

Laravel 5 - Undefined property when using relationships

我从一个基本查询开始,该查询从 table:

返回项目数据
$project = Project::find($id);
return view('project.show')->with('project', $project);

然后在我的页面上我 dd()$project->id 并且它起作用了。

我现在也有一个叫 table 的用户。

一个项目属于一个用户,所以我在我的模型中设置了一个关系:

public function user()
{
    return $this->belongsTo('App\User');
}

然后我做:

$project = Project::with('user')->where('id', $id)->get();

但是我得到错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$id

如果我只是 dd() $project:

Collection {#200 ▼
    #items: array:1 [▼
    0 => Project {#196 ▼
      #fillable: array:1 [▶]
      #dates: array:2 [▶]
      #connection: null
      #table: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:5 [▶]
      #original: array:5 [▶]
      #relations: array:1 [▶]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    ]
}

我做错了什么?

为了澄清,我希望能够做到:

$project->id
$project->user->name

试试

$project = Project::with('user')->find($id);

我会这样做:

控制器:

Project::where('id', $id)->get();

型号

public function user(){
return $this->belongsTo(User::class);
}

查看

@foreach($project as $i)
 {{ $i->user->user_id }}

get() 方法将始终 return 一个 Illuminate\Database\Eloquent\Collection 对象。这意味着您的 $project 变量是 Collection,因此当您尝试 $project->id 时,您正在尝试访问 Collection 上的 id 属性,这不存在。这就是您收到错误的原因。

有几种不同的方法可以实现您想要做的事情。它们显示在下面的代码中。它们都差不多。

// This is your code, just added the call to first() on the Collection
// to get the first item in the Collection
$project = Project::with('user')->where('id', $id)->get()->first();

// This is a little more efficient. It is calling first() on the QueryBuilder.
// This will directly return the desired object, without having to create
// an intermediate Collection.
$project = Project::with('user')->where('id', $id)->first();

// This is equivalent to the previous statement, just a little cleaner.
// find() is just a shortcut for where('id', $id)->first().
$project = Project::with('user')->find($id);

上述所有三个语句都将为您提供 Project 对象,然后您可以随意使用它:

$project = Project::with('user')->find($id);

// print the id
echo $project->id.PHP_EOL;

// if the user exists, print the name
if ($project->user) {
    echo $project->user->name.PHP_EOL;
}