gpt4 book ai didi

php - 如何处理 laravel 中与同一张表的对称关系?

转载 作者:行者123 更新时间:2023-12-05 07:23:49 25 4
gpt4 key购买 nike

我的 Laravel 项目中有一个产品表,产品。我还有另一个表,product_assocs:

CREATE TABLE `product_assocs` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`product_id_primary` bigint(20) UNSIGNED DEFAULT NULL,
`product_id_assoc` bigint(20) UNSIGNED DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

这让我可以将相关产品相互联系起来。我希望这些关系是对称的。也就是说,如果您在 product_assocs 表中创建一个记录,它会创建一个双向工作的关系。

我在我的产品模型中定义了一个方法来获取关联产品的 ID:

$associationsForProduct = $product->associated()->get();

此方法利用 Products 模型中的函数,如下所示:

public function associated() {
return $this->belongsToMany(Product::class, 'product_assocs', 'product_id_primary', 'product_id_assoc');

我在执行这种“laravel 方式”时遇到了一些麻烦。显然,当我获取特定产品 $id 的关联产品时,我必须获取 product_assocs 中 id1=$id OR id2=$id 的所有记录。我可以想象一个老式的 PHP 循环可以完成这个:

// assume $assocs is an array of records fetched where product_id_primary=$id or product_id_assoc=$id
// assume $id is the current product for which we are fetching records
$clean = array();
foreach($assocs as $asc) {
if ($asc["product_id_primary"] != $id && !in_array($asc["product_id_primary"], $clean)) {
$clean[] = $asc["product_id_primary"];
}
if ($asc["product_id_assoc"] != $id && !in_array($asc["product_id_assoc"], $clean)) {
$clean[] = $asc["product_id_assoc"];
}

}

我是否理解如果我在 Product 模型中创建一个互惠函数来查询数据透视表中的第二个 ID,我是否可以以某种方式在 Controller 中加入该函数?也许是这样的:

public function related() {
return $this->belongsToMany(Product::class, 'product_assocs', 'product_id_assoc', 'product_id_primary');

那么如何正确地制定 Controller 语句以便它在此处查找 associated() 和 related() 函数中的关系:

$associationsForProduct = $product->[--associated()--OPERAND --related()]->get();

我想知道是否有更好的方法来实现这一目标。 谁能告诉我建议如何在 Laravel 中处理这个问题?

最佳答案

在 friend 的帮助下,我设法解决了这个问题。我在我的产品 Controller 中遗漏了反向关系。

if (method_exists($data, 'associated')) {
$association = ($request->has('association')) ? $request->get('association') : [];
$data->associated()->sync($association);

// create the inverse relationships
$associated = Product::whereIn('id', $association)->get()->each(function($product) use ($data) {
// doing a remove first to prevent duplicate entries
$product->associated()->detach($data->id);
$product->associated()->attach($data->id);
});
}

关于php - 如何处理 laravel 中与同一张表的对称关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com