【发布时间】:2020-01-21 11:51:09
【问题描述】:
当我返回时我与集合的关系总是空的,我的数据库中确实有数据。
客户端模型
public function orders()
{
return $this->belongsToMany(Service::class)->withTimestamps();
}
服务模式
public function clients()
{
return $this->belongsToMany(Client::class)->withTimestamps();
}
查询关系始终为空
$client = Client::with('orders')->firstOrFail();
我的表迁移;
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
]
]
【问题讨论】:
-
您的代码看起来不错。在查询
\DB::enableQueryLog();之前和查询dd(\DB::getQueryLog())之后启用查询日志。它应该打印两个执行的查询。 -
如果下面的答案不起作用。将函数名称从
orders()更改为services()然后当然而不是::with('orders')改为::with('services') -
@Sam 查询看起来不错。尝试直接从 phpMyAdmin 或您使用的任何方式运行第二个查询。如果它没有返回任何结果,那么问题出在您的数据上。也许
client_service表不包含所需的行。 -
@UrošAnđelić 我在 SQL 中运行查询并正确返回结果
标签: database laravel eloquent laravel-6