繁体   English   中英

Laravel 5.1将雄辩的关系应用于Tinker中找不到的模型引发类

[英]Laravel 5.1 Applying Eloquent Relationships to Models Throws Class Not Found in Tinker

我正在观看Laravel 5.x Laracast视频系列,现在它是关于建立雄辩的关系的,除了所涉及的类之外,我的写作完全相同,但是我不断得到“找不到类应用程序\\车辆尝试进行修补时测试此错误。 没错,没有Vehicles模型,但是由于模型是奇异的,所以我不确定为什么会引发错误。 我已经运行了作曲家dump-autoload,所以不是没有看到文件。

用户模型

/**
 * A user can have many vehicles.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function vehicles() {

    return $this->hasMany('App\Vehicle');
}

车辆型号

/**
 * A vehicle is owned by a user
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function owner()
{
    return $this->belongsTo('App\User');
}

数据库迁移和种子成功,并且我已经验证了种子中是否存在数据库记录。

修补匠

$user = App\User::first(); // provides the proper user with id = 1
$vehicle = App\Vehicle::first(); // provides the proper vehicle with user_id of 1

$user->vehicles->toArray(); // Throws the "Class App\Vehicles Not Found error"

我已经观看了3次视频以尝试发现任何问题,除了将模型命名为Vehicle而不是Article之外,没有任何区别。

UPDATE

在第一个问题的帮助下,此问题得以解决,但致电:

App\Vehicle::first()->owner->toArray();

在belongsTo关系上抛出一个错误,说:

[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function toArray() on null

我花了一段时间,最后是garethdaine ,花了一段时间才能通过反复试验弄清楚这一点,才发现哈哈文档中确实对此有一段论述。 开始:

owner关系无法找到任何相应的用户,因为它正在寻找错误的列。

Eloquent通过检查关系方法的名称并在方法名称后加上_id来确定默认的外键名称。 但是,如果Phone模型上的外键不是user_id,则可以将自定义键名称作为第二个参数传递给belongsTo方法:

/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo('App\User', 'foreign_key');
}

在您的情况下,它正在寻找owner_id而不是user_id 因此,可以按照示例将方法重命名为user或指定'foreign_key'参数。

您可以通过键入dd(App\\Vehicle::first()->owner)来查看关系模型,其中包含由Eloquent设置的foreign_key属性。

另外,还要考虑寻找到渴望延迟加载解决N + 1问题。

首先获取车辆对象,然后调用所有者模型,如下所示

$vehicle = App\Vehicle::first();
$vehicle->owner->toArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM