【问题标题】:Laravel many to many relationship collection emptyLaravel 多对多关系集合为空
【发布时间】: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


【解决方案1】:

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

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();
});

【讨论】:

  • 谢谢你这解决了我的问题,我不明白为什么我认为我遵循了 Laravel 命名约定,所以这有效?
  • @Sam 很高兴您解决了您的问题,但 Eloquent 不会检查是否有外键。有趣的情况。
  • @UrošAnđelić 确实如此。您只需要设置关系方法。但我喜欢设置外键,这样我就不会得到孤立行等。不知道为什么它对他不起作用。
猜你喜欢
  • 2019-01-04
  • 2019-06-22
  • 2020-07-21
  • 2019-11-27
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
相关资源
最近更新 更多