作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试检索数据库行及其关系。但是,本地键是一个数组。让我用一个例子来解释。
假设我有一张国家表格和一张网页表格。每个国家可以有很多页面。每个页面可以属于多个国家。我没有更改此模式的灵 active 。
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 |
+----+----------------+
我的模型和 Controller 看起来像这样:
country
public function pages()
{
return $this->hasMany(Page::class, 'id', 'countries');
}
MemberController.php
$countries = Country::with('pages')->get();
这将返回所有国家,但只有第 1 页包含任何关系。
有没有办法使用 whereIn 方法检索关系,以便所有三个国家/地区都返回适当的页面?
提前致谢
最佳答案
由于 Page
可以属于许多 Countries
,您需要创建一个名为 country_page
的数据透视表并删除 countries
列。
然后定义两个belongsToMany()
两种模型中的关系:
public function pages()
{
return $this->belongsToMany(Page::class);
}
如果你是 not following Laravel naming conventions在我的 repo 中列出并且你给了 pivot 名称一个自定义名称,也定义它:
public function pages()
{
return $this->belongsToMany(Page::class, 'custom_pivot_table');
}
关于拉拉维尔。如何获得外键是数组的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49048041/
我正在使用 git clone 部署我的 Laravel 项目并使用 git pull 进行更新 它工作正常,但每次部署时,我都必须从 config/app.php providers 数组和 ali
我是一名优秀的程序员,十分优秀!