Laravel 多对多关系集合为空

Laravel many to many relationship collection empty

当我 return 与我的关系与集合总是空的时,我的数据库中确实有数据。

客户端模型

public function orders()
{
    return $this->belongsToMany(Service::class)->withTimestamps();
}

服务模式

public function clients()
{
    return $this->belongsToMany(Client::class)->withTimestamps();
}

查询关系始终为空

$client = Client::with('orders')->firstOrFail();

我的table迁移;

Schema::create('client_service', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('client_id');
    $table->unsignedBigInteger('service_id');
    $table->timestamps();
});

使用上面的多对多设置,我看不出关系是空的。

查询日志

array:2 [▼
  0 => array:3 [▼
    "query" => "select * from `clients` limit 1"
    "bindings" => []
    "time" => 0.59
  ]
  1 => array:3 [▼
    "query" => "select `services`.*, `client_service`.`client_id` as `pivot_client_id`, `client_service`.`service_id` as `pivot_service_id`, `client_service`.`created_at` as `pivot_created_at`, `client_service`.`updated_at` as `pivot_updated_at` from `services` inner join `client_service` on `services`.`id` = `client_service`.`service_id` where `client_service`.`client_id` in (1) ◀"
    "bindings" => []
    "time" => 1.05
  ]
]

您需要设置外键。其他一切看起来都不错,应该可以工作。

Schema::create('client_service', function (Blueprint $table) {
    $table->bigIncrements('id');

    $table->unsignedBigInteger('client_id');
    $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');

    $table->unsignedBigInteger('service_id');
    $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade');

    $table->timestamps();
});