首页 > 解决方案 > Laravel 与 uuid 的多对多关系返回总是空的

问题描述

我使用 Laravel 5.8 并将模型的自动增量 ID 更改为 uuid。Event从那以后,我在我的两个模型和User(使用数据透视表events_users)之间定义的多对多关系遇到了一些麻烦。

问题: 现在,当我请求加入两个表的所有元素(我的数据透视表中有 2 条记录)时,我总是得到一个空数组。在调试 sql 时,我看到未设置 where 子句参数:

// Generated sql
select `users`.*, `events_users`.`event_id` as `pivot_event_id`, `events_users`.`user_id` as `pivot_user_id`, `events_users`.`created_at` as `pivot_created_at`, `events_users`.`updated_at` as `pivot_updated_at`
from `users`
inner join `events_users` on `users`.`id` = `events_users`.`user_id`
where `events_users`.`event_id` = ?

// Bindings :
Array
(
    [0] => 
)

有人知道我在这里缺少什么吗?

这是我的模型的定义:

class Event extends Model
{
    protected $primaryKey = 'id';
    protected $keyType = 'string';
    public $incrementing = false;

// here some other model methods, fillable property, etc.


public function users()
{
    return $this
        ->belongsToMany(User::class, 'events_users', 'event_id', 'user_id')
        ->withTimestamps();
}

}

用户模型的相同声明,但有关系

public function events()
{
    return $this
        ->belongsToMany(Event::class, 'events_users', 'user_id', 'event_id')
        ->withPivot(['created_at', 'updated_at']);
}

然后我从服务中检索关系:

public function getSubscriptions($eventId)
{
    $eventId = 'a1b7c5d6-8f86-44f4-f31a-46e32917d5c0'; // for debug purpose only
    $event = Event::find($eventId);

    foreach ($event->users as $user) {
        print_r($user); die; // It never loops here as its length is 0 but should be 2...
    }

    \DB::listen(function ($query) {
        print_r($query->sql);
        print_r($query->bindings);
        // $query->time
    });

    $subscriptions = $event
        ->users()
        ->get();
    die;

    return $subscriptions;
}

我的数据库包含记录

标签: laravellaravel-5eloquentmany-to-manyrelationship

解决方案


问题是关于我列出属性的模型中的另一个声明。我已经在id那里初始化了一个属性,它可能与 uuid 类型冲突,或者我不知道究竟是什么原因导致了这出戏剧......无论如何,删除这一行让应用程序正常工作。

/**
 * @var array
 * Rules used for fields validation
 */
public $rules = array(
    'title'       => 'required|string|max:255',
    'start_date'  => 'required|date|date_format:Y-m-d',
    'end_date'    => 'required|date|date_format:Y-m-d|after_or_equal:start_date',
    'location'    => 'string|max:254',
    'latitude'    => 'numeric',
    'longitude'   => 'numeric'
);

public $id          = "";  // This is the line that create the bug... Remove it and it works !
public $title       = "";
public $start_date  = "";
public $end_date    = "";
public $location    = "";
public $latitude    = "";
public $longitude   = "";

推荐阅读