有没有人找到解决方案来尝试获取非对象的属性“枢轴”?

Posted

技术标签:

【中文标题】有没有人找到解决方案来尝试获取非对象的属性“枢轴”?【英文标题】:Did anyone find solution for Trying to get property 'pivot' of non-object? 【发布时间】:2020-09-16 17:31:33 【问题描述】:

我尝试使用数据透视表建立关系 btw 组织者和用户,但是当我尝试显示输出时,它显示错误。 OrganizeController.php

public function show($id)

    $organize = Organize::find($id);

    return dd($organize->pivot->name);

组织.php

namespace App;

use App\OrganizeUser;

use Illuminate\Database\Eloquent\Model;

class Organize extends Model

    public function user()
    
        return $this->belongsToMany(User::class)->withPivot('user_id');
    

【问题讨论】:

如果您的关系是多对多的,您不需要在模型中使用 ->withPivot('user_id') 并访问它,您需要有类似 `return dd($organize->users); 之类的东西。 ` 错误是什么? 【参考方案1】:

试试这个:

public function show($id)
    $organize = Organize::find($id);
    $organize->user()->get();

【讨论】:

以上是关于有没有人找到解决方案来尝试获取非对象的属性“枢轴”?的主要内容,如果未能解决你的问题,请参考以下文章