Laravel与uuid的多对多关系始终为空

时间:2019-05-14 06:07:55

标签: laravel laravel-5 eloquent many-to-many relationship

我使用Laravel 5.8,并将模型的自动增量ID更改为uuid。从那时起,我在模型EventUser(使用数据透视表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;
}

我的数据库包含记录

1 个答案:

答案 0 :(得分:1)

问题出在我列出属性的模型中的另一个声明。 我在那里初始化了一个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   = "";