【问题标题】:Laravel 8 seeding property [id] does not exist on the Eloquent builder instanceLaravel 8 播种属性 [id] 在 Eloquent 构建器实例上不存在
【发布时间】:2021-07-25 11:17:58
【问题描述】:

我正在为客户重建一个旧项目并将其移动到 Laravel 8。我已经创建了所有模型并将当前项目中的所有数据转换为 json,以便我可以将数据作为播种数据迁移。

我有一个Usercar 模型,它与CarUser 模型有belongsTo 关系。我需要在播种过程中通过比较和匹配旧的 id 值来重新创建关系,以便创建新的记录和关系。我所有的播种机都成功运行,直到我到达 **UsercarSeeder**,然后我收到 property [id] does not exist on the Eloquent builder instance 错误。我知道我错过了一些非常简单的东西。谢谢。

database/data/cars.json

[
    {
        "old_car_id": 31,
        "start_year": 1955,
        "end_year": 1958,
        "model": "356  Carrera 1500 GS Coupe",
        "horse_power": 110,
...

数据库/数据/users.json

[
    {
        "old_user_id": "4be7c3a7-d626-456a-83be-5d303bf90d02",
        "first_name": "Charles",
        "last_name": "Smith",
...

database/data/user-cars.json

[
    {
        "old_user_id": "4be7c3a7-d626-456a-83be-5d303bf90d02",
        "old_car_id": 227,
        "car_color": "Gray",
        "year": 2015,
        "tire_points": 140,
...

数据库/seeders/UsercarSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Car;
use App\Models\Usercar;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class UsercarSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $json = file_get_contents('database/data/user-cars.json');
        $data = json_decode($json);

        $user = User::where('old_user_id', 'old_user_id')->get();
        $car = Car::where('old_car_id', 'old_car_id')->get();

        foreach ($data as $obj) {
            Usercar::create(array(
                'user_id' => $user->id,
                'car_id' => $car->id,
...

【问题讨论】:

  • 我真的不明白,但问题是id,我认为在'user_id' =&gt; $user-&gt;id
  • 为什么你在新表中有old_user_id?最好只有id

标签: php laravel


【解决方案1】:

get() 方法返回模型集合。如果您需要单个对象,则应使用first() 方法。

where() 也应该类似于:

->where($column, $value)

看起来您将列名传递了两次,这可能会返回一个空集合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2022-01-15
    • 2020-08-02
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多