Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 拉威尔:旅行以获得财产';职位';非对象_Laravel_Laravel 5.7 - Fatal编程技术网

Laravel 拉威尔:旅行以获得财产';职位';非对象

Laravel 拉威尔:旅行以获得财产';职位';非对象,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

我想显示用户的帖子。但是,我收到一条错误消息:试图获取非对象的属性“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('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,如果答案对你有用,你可以接受。