php Laravel - 调用未定义的方法 Illuminate\Database\Query\Builder::user()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37933861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:26:04  来源:igfitidea点击:

Laravel - Call to undefined method Illuminate\Database\Query\Builder::user()

phpsqlitelaravel

提问by Clinton Green

I am busy with Laravel From Scratch: Updating Records and Eager Loading. I have followed the tut but I am getting this error when trying to add user data in CardsController. I am assuming that I've missed a step in the card user relationship somewhere but I've watched the video 3 times and my database queries for User, Card & Note matches the video exactly.

我正忙于Laravel From Scratch: Updating Records and Eager Loading。我遵循了 tut,但在尝试在 CardsController 中添加用户数据时出现此错误。我假设我在某处错过了卡片用户关系中的一个步骤,但我已经观看了 3 次视频,并且我对用户、卡片和笔记的数据库查询与视频完全匹配。

Is there another step I need to perform after creating the Users table via the migration perhaps?

在通过迁移创建用户表之后,我还需要执行另一个步骤吗?

Error

错误

BadMethodCallException in Builder.php line 2345:

Call to undefined method Illuminate\Database\Query\Builder::user()

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

CardsController code

CardsController 代码

<?php
namespace App\Http\Controllers;
use App\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CardsController extends Controller
{
    public function index()
    {
        $cards = Card::all();
        return view('cards.index', compact('cards'));
    }

    public function show(Card $card)
    {
        $card = Card::with('notes.user')->get();
        return $card;
        return view('cards.show', compact('card'));
    }
}

回答by Ohgodwhy

Your notemodel is lacking the relationship definition for it's associated user, it looks like.

您的note模型缺少关联的关系定义user,看起来像。

You should just be able to add the relationship in the Notesmodel like this:

您应该能够Notes像这样在模型中添加关系:

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

回答by lightWay

That video does have some problems, so I also encountered the same problem. You should just be able to add the relationship in the Note model like this:

那个视频确实有问题,所以我也遇到了同样的问题。您应该能够像这样在 Note 模型中添加关系:

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

and in the User model like this:

在像这样的用户模型中:

public function notes()
{
    return $this->hasMany(Note::class);
    //return $this->belongsTo('App\Note');
}

bless you !

祝福你 !