Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.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
Php 拉维尔后所有者关系_Php_Laravel_Laravel 5.6 - Fatal编程技术网

Php 拉维尔后所有者关系

Php 拉维尔后所有者关系,php,laravel,laravel-5.6,Php,Laravel,Laravel 5.6,我有类别内容,内容和用户表格,每个内容属于多个类别内容,类别内容属于多个内容,每个内容属于一个用户,一个用户在内容表格上有多个帖子 class Contents extends Model { ... public function categories() { return $this->belongsToMany(ContentCategories::class); } public function user() {

我有
类别内容
内容
用户
表格,每个
内容
属于多个
类别内容
类别内容
属于多个
内容
,每个
内容
属于一个用户,一个用户在
内容
表格上有多个帖子

class Contents extends Model
{
    ...

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }

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

class ContentCategories extends Model
{
    ...

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

class User extends Authenticatable
{
    ...

    public function content()
    {
        return $this->hasMany(Contents::class);
    }
}
通过下面的代码,我可以找到类别id为
7

$nodejsContents = ContentCategories::find('7')->contents;
现在,问题是,如何在这个查询中获得帖子所有者,哪个内容属于哪个用户

我测试了此代码,但发现错误:

$nodejsContents = ContentCategories::find('7')->contents->user;
错误:

"Undefined property: Illuminate\Database\Eloquent\Builder::$contents"
内容\u类别
迁移:

public function up()
{
    Schema::create('contents_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('lang',2)->default('fa');
        $table->integer('parent')->default(0);
        $table->timestamps();
    });
}

用户
内容
中,因此通过闭包访问

$nodejsContents = ContentCategories::has('contents')->with(['contents' => function($query){
                                        $query->with('user')->get();
                                    }])->find('7');
belongToMany
Contents将返回一个集合。因此,您可以在集合中循环以获取
内容的相关用户


能否添加
ContentCategories
模型的表/迁移/模式结构?这里
user
是什么
find('7')->contents->user@C2486它只用于测试,我得到error@Quezlerpost Updated但是
用户
内容
集合的值类型在此为空,感谢此帖子解决了我的问题
ContentCategories::find(7)->contents->with('user')
是正确的如果你碰巧是某个人对我的回答投了反对票,你能解释一下原因吗?我对你的帖子投了赞成票而不是反对票,我不知道是谁对你的帖子投了反对票:(
ContentCategories::find('7')->contents
ContentCategories::find(7)->contents->with('user');