Laravel 拉威尔:旅行以获得财产';职位';非对象
我想显示用户的帖子。但是,我收到一条错误消息:试图获取非对象的属性“posts” User.phpLaravel 拉威尔:旅行以获得财产';职位';非对象,laravel,laravel-5.7,Laravel,Laravel 5.7,我想显示用户的帖子。但是,我收到一条错误消息:试图获取非对象的属性“posts” User.php public function posts() { return $this->hasMany(Post::class, 'author_id', 'id'); } public function author() { return $this->belongsTo(User::class, 'author_id', 'id'); } Route::get('tes
public function posts()
{
return $this->hasMany(Post::class, 'author_id', 'id');
}
public function author()
{
return $this->belongsTo(User::class, 'author_id', 'id');
}
Route::get('test', function () {
$user = User::find(5);
return $user->posts;
});
Post.php
public function posts()
{
return $this->hasMany(Post::class, 'author_id', 'id');
}
public function author()
{
return $this->belongsTo(User::class, 'author_id', 'id');
}
Route::get('test', function () {
$user = User::find(5);
return $user->posts;
});
web.php
public function posts()
{
return $this->hasMany(Post::class, 'author_id', 'id');
}
public function author()
{
return $this->belongsTo(User::class, 'author_id', 'id');
}
Route::get('test', function () {
$user = User::find(5);
return $user->posts;
});
作者是一个什么样的独立模型? 首先,您需要创建一个适当的迁移,以便在posts表中将
user\u id
作为外键引用
您应该有一个类似于此的向上迁移方法:
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
您的模型可以是这样的:
class Post extends Model
{
/**
* Get the user record associated with the post.
*/
public function user()
{
return $this->hasOne('App\User');
}
}
现在,您应该能够调用
$post->user
,对于您的用例,我不知道作者是什么,但您应该能够修改我的answe,祝您好运。您的数据库中是否有id为5的用户?请使用App\post
而不是post::class
和App\user
,而不是user::class
。它应该可以工作(注意:您应该提供您的模型的地址,在默认模式下它位于“App”文件夹中,因此它的地址是App\ModelName
)“author\u id”表示“user\u id”@SerdarPolat,然后请将其命名为user\id
@SerdarPolat。您还需要将author()
函数重命名为user()
laravel会自动检测到它,并将其与现有系统进行比较models@SerdarPolat,如果答案对你有用,你可以接受。