【问题标题】:Property [column] does not exist on this collection instance此集合实例上不存在属性 [列]
【发布时间】:2021-05-02 00:57:49
【问题描述】:

无法访问 Laravel Eloquent 关系


使用get()方法时

        $user = User::find(1)->get(); 
        
        $foo = $user->posts->title;

此集合实例上不存在属性 [posts]。


使用first()方法后

        $user = User::find(1)->first(); 
        
        $foo = $user->posts->title;

或者


        $user = User::with('posts')->first(); 
        
        $foo = $user->posts->title;

此集合实例上不存在属性 [title]。


文件和配置

App\Models\User.php

namespace App\Models;

use App\Models\Post;

class User extends Model
{

    public function posts(){

        return $this->hasMany(
                                Post::class, 
                                'post_code', 
                                'code'
                            );
    }

}

App\Models\Post.php

namespace App\Models;


class Post extends Model
{

    protected $fillable = ['title', 'code', 'tags'];
    
}


Post 表,其中id 字段为 PK。但我想与code 字段建立关系。

id title code tags
1 Monalisa MH01 arts
2 AI MH01 science

User 表,其中post_code 与Post 表有很多关系。

id name post_code
1 John MH01

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

find 方法是这样的

public function find($id, $columns = ['*'])
{
    if (is_array($id) || $id instanceof Arrayable) {
        return $this->findMany($id, $columns);
    }

    return $this->whereKey($id)->first($columns);
}

此方法首先返回,所以你需要这样做$user = User::find(1);,这将返回用户。

【讨论】:

    【解决方案2】:

    find() 给你一个模型实例,findOrFail() 给你一个模型实例 + 如果数据为空,它将引发 404 错误:

    $user = User::findOrFail(1);
    

    一个用户有很多posts(),所以你需要做一个循环来获取数据。在检查关系是否有数据之前,否则会抛出错误:

    if($user->posts()->exists()) {
       foreach($user->posts as $key => $value){
              echo $value->title;
       }
    }
    

    【讨论】:

    • 如果您可以建议其他方法,它对find() 不是强制性的。这样就可以了。
    【解决方案3】:

    我想感谢Original Answer。

    get() 将提供集合,first() 提供对象。因此,我使用了first() 方法和with('relation') 方法,它接受relation 名称作为参数。

    我们可以通过[]操作符使用它的索引来访问它

            $user = User::with('posts')->first(); 
            
            $title = $user->posts[0]->title;
            $name = $statements->name;
    
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2019-03-23
      • 2020-07-11
      • 2017-05-12
      • 2018-10-12
      • 2021-02-08
      • 2021-12-16
      相关资源
      最近更新 更多