【问题标题】:Laravel - SQL query equals the value of id to null in many to many relationshipLaravel - SQL查询在多对多关系中等于id的值为null
【发布时间】:2018-11-22 22:44:57
【问题描述】:

在模型中我有:

class Car extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'car_user', 'car_id', 'user_id');
    }
}

在我的控制器中,我有:

\DB::enableQueryLog();
$cars = Car::with('users')->get();
dd(\DB::getQueryLog());

执行的查询是:

array:2 [▼
  0 => array:3 [▼
    "query" => "select * from `cars`"
    "bindings" => []
    "time" => 0.62
  ]
  1 => array:3 [▼
    "query" => "select `users`.*, `car_user`.`user_id` as `pivot_user_id`, `car_user`.`car_id` as `pivot_car_id` from `users` inner join `car_user` on `users`.`user_id` = `car_user`.`car_id` where `car_user`.`user_id` in (?)"
    "bindings" => array:1 [▼
      0 => null
    ]
    "time" => 0.6
  ]
]

问题是第二个查询中的bindings 值为空。我想获取所有 cars 并迭代到它们中的每一个,并让每辆车拥有尽可能多的用户。

我该怎么做?

编辑 表架构:

汽车用户: car_id user_id

汽车: car_id car_code 价格

用户: user_id user_type 用户名密码

谢谢

【问题讨论】:

  • 简单来说,您希望一辆车有多个用户?
  • many-to-many => 我想拥有所有汽车和与之相关的所有用户。一辆车可以有多个用户,一个用户可以有多辆汽车。
  • 是的 明白了,通过上面的查询,您正试图让所有汽车及其用户正确?
  • 你能不能也给我看看表结构?
  • 是的,没错!

标签: laravel many-to-many relationship


【解决方案1】:

由于您使用的是自定义主键,因此您必须在模型中指定它们:

class Car extends Model
{
    protected $primaryKey = 'car_id';
}

class User extends Model
{
    protected $primaryKey = 'user_id';
}

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 2015-05-29
    • 1970-01-01
    • 2019-02-07
    • 2013-09-14
    • 2020-12-15
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多