【问题标题】:Get data from pivot table eloquent从数据透视表 eloquent 中获取数据
【发布时间】:2018-10-15 12:05:00
【问题描述】:

我正在尝试从数据透视表中获取数据,但它显示“尝试获取非对象的属性‘标签’”。即使表中有一些数据,控制器中的 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;
    }

有人可以帮忙吗?

【问题讨论】:

    标签: database laravel eloquent


    【解决方案1】:

    Videos::find(1) 正在尝试查找 id = 1 的视频,如果未显示,则不返回任何内容并且您遇到异常,您可以使用 findOrFail(1)

    findOrFail 将抛出模型未找到异常,您希望这种情况发生,否则您将尝试访问非对象上的属性。

    在您的关系中,您必须指定要包含的列:

    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();在控制器中。谢谢你:)
    猜你喜欢
    • 2019-09-29
    • 2020-11-09
    • 2015-12-09
    • 1970-01-01
    • 2017-07-25
    • 2016-11-21
    • 2019-07-25
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多