Laravel。如何获得外键是数组的关系

问题描述 投票:1回答:1

我试图用他们的关系检索数据库行。但是,本地密钥是一个数组。让我用一个例子来解释。

可以说我有一张国家表和一张表。每个国家/地区可以有很多页面每个页面可以属于多个国家/地区。我无法灵活地更改此架构。

pages
+-------------+-----------+
| id | name   | countries |
+-------------+-----------+
| 1  | Page 1 | 1         |
+-------------+-----------+
| 2  | Page 2 | 1,2,3     |
+-------------+-----------+
| 3  | Page 3 | 4,5,6     |
+-------------+-----------+

countries
+----+----------------+
| id | name           | 
+----+----------------+
| 1  | United States  |
+----+----------------+
| 2  | United Kingdom |
+----+----------------+
| 3  | Germany        |
+----+----------------+
| 4  | France         |
+----+----------------+
| 5  | Hong Kong      |
+----+----------------+
| 6  | Thailand       |
+----+----------------+
| 7  | Belgium        |
+----+----------------+
| 8  | Singapore      |
+----+----------------+

我的模型和控制器看起来像:

country 

public function pages()
{
    return $this->hasMany(Page::class, 'id', 'countries');
}

MemberController.php

$countries = Country::with('pages')->get();

这将返回所有国家/地区,但只有第1页包含任何关系。

有没有办法使用whereIn方法检索关系,这样所有三个国家都将返回适当的页面?

提前致谢

laravel relationship
1个回答
0
投票

由于Page可以属于许多Countries,您需要创建一个名为country_page的数据透视表并删除countries列。

然后在两个模型中定义两个belongsToMany()关系:

public function pages()
{
    return $this->belongsToMany(Page::class);
}

如果您在我的仓库中列出了not following Laravel naming conventions并且您为枢轴名称指定了自定义名称,请同时对其进行定义:

public function pages()
{
    return $this->belongsToMany(Page::class, 'custom_pivot_table');
}
© www.soinside.com 2019 - 2024. All rights reserved.