Database 从数据透视表中获取数据

Database 从数据透视表中获取数据,database,laravel,eloquent,Database,Laravel,Eloquent,我试图从pivot表中获取数据,但它说“试图获取非对象的属性‘标记’”。此外,即使表中有一些数据,控制器中的find(1)也不会返回任何内容 我的模型: class Videos extends Model { protected $table = 'videos'; function tags(){ return $this->belongsToMany('App\Models\Videos\Tags','tag_video','video_id','ta

我试图从pivot表中获取数据,但它说“试图获取非对象的属性‘标记’”。此外,即使表中有一些数据,控制器中的find(1)也不会返回任何内容

我的模型:

class Videos extends Model
{
    protected $table = 'videos';
    function tags(){
        return $this->belongsToMany('App\Models\Videos\Tags','tag_video','video_id','tag_id');

    }


class Tags extends Model
{

    function videos(){
        return $this->belongsToMany('App\Models\Videos\Videos','tag_video', 'tag_id','video_id');
    }
}
我的控制器:

 public function fetch(){
        $videos_from_supercategories =
        $videos_with_tags = Videos::find(1);
        $tags = $videos_with_tags->tags->first();

      $data['tags']=$tags;

        return $data;
    }
有人能帮忙吗?

视频::查找(1)
正在尝试查找id=1的视频,如果未显示,它将不返回任何内容,并且您得到异常,您可以使用
查找失败(1)

findOrFail将引发model not found异常,您希望发生这种情况,因为否则您将尝试访问非对象的属性

在关系中,必须指定要包括的列:
public function fetch()
{
    return Videos::findOrFail(1)->tags->first()->pivot->column1;
}

class Videos extends Model
{
    protected $table = 'videos';
    function tags()
    {
        return $this->belongsToMany('App\Models\Videos\Tags','tag_video','video_id','tag_id')->withPivot('column1', 'column2');
    }
}

在模型中使用withPivot会有所帮助,但我必须使用:$tags=Videos::with('tags')->get();在控制器中。谢谢:)