【问题标题】:Laravel Undefined MethodLaravel 未定义方法
【发布时间】:2019-04-21 02:31:58
【问题描述】:

当我的模型中存在兴趣方法时,我的查询出现以下错误。

调用未定义的方法 Illuminate\Database\Query\Builder::interest()

控制器:

public function index() {
    $user_id = auth()->user()->id;
    $user = User::find($user_id);

    $interests = Space::where('user_id', $user_id)->interest()->get();

    return view('dashboard')->with('space', $user->space)->with('interest', $interests->space);
}

空间模型:

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

public function interest(){
    return $this->hasMany(Interest::class);
}

兴趣模型:

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

public function interest(){
    return $this->belongsTo(Space::class);
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:
    Space::where('user_id', $user_id)->interest()->get();
    

    该行显示错误,因为方法 interest 在查询构建器或模型范围中不存在

    但我认为你误解了一些东西

    在集合中加载关系

    Space::where('user_id', $user_id)->with('interest')->get();
    

    会工作

    还有

    $singleFind = Space::findOrFail($yourId)->interest();
    

    会按预期工作

    希望清楚

    【讨论】:

      【解决方案2】:

      试试这个, 首先,您可以通过 auth()->id() 访问经过身份验证的用户 ID

      对于控制器中的关系

          $interests = Space::with(['interest'])->where('user_id', $user_id)->get();
      

      更多 Laravel eager loading

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 2022-12-23
        • 2021-09-16
        • 2018-01-11
        • 2019-08-18
        • 2021-08-02
        • 2017-02-01
        • 2021-08-29
        • 2013-10-23
        • 2018-10-31
        相关资源
        最近更新 更多