【发布时间】: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 |
【问题讨论】:
-
不应该只是
User::find(1);之后没有任何东西吗? laravel.com/docs/8.x/eloquent#retrieving-single-models -
$user = User::findOrFail(1);然后$user->getAddress->city;