【问题标题】:Laravel 5 - Undefined property when using relationshipsLaravel 5 - 使用关系时未定义的属性
【发布时间】:2015-11-18 13:26:44
【问题描述】:

我从一个从表中返回项目数据的基本查询开始:

$project = Project::find($id);
return view('project.show')->with('project', $project);

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

我现在还有一个名为 user 的表。

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

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

然后我会这样做:

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

但我得到了错误:

未定义属性: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

【问题讨论】:

标签: php laravel laravel-5 eloquent relationship


【解决方案1】:

get() 方法将始终返回一个 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;
}

【讨论】:

  • 感谢您花时间解释 :) 为我解决了问题。
【解决方案2】:

我会这样做:

控制器:

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

型号

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

查看

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

【讨论】:

    【解决方案3】:

    试试类似的东西

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

    【讨论】:

    • 此语句将返回所有项目,所有用户都急切地加载。 find() 将返回一个模型实例,但随后调用 with() 将返回一个新的查询构建器,然后您调用 get() 将返回所有项目。
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 2017-07-29
    • 2020-01-28
    • 2017-07-07
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多