sql - Laravel 7 查询关系表
问题描述
我需要一些帮助来从有关系的表中获取数据。
我有 2 张桌子:卡片和状态:
我在卡片表中有以下数据:
id_card | card_type
--------|----------
123 | tag
281 | card
455 | card
721 | tag
在状态表中,我有:
id_status | id_card | status_date | status_type | status_company | status_user
----------|---------|-------------|-------------|----------------|------------
1 | 123 | 2018-12-04 | available | |
2 | 281 | 2018-12-04 | available | |
3 | 455 | 2018-12-04 | available | |
4 | 721 | 2019-03-26 | available | |
5 | 281 | 2020-01-25 | issued | Company A | User One
6 | 123 | 2020-01-10 | issued | Company B | User Two
7 | 281 | 2020-01-25 | available | |
8 | 123 | 2020-02-02 | lost | |
9 | 455 | 2020-02-14 | issued | Company C | Third User
对于卡片模型,我在卡片模型中有以下内容:
public function Status() {
return $this->hasMany('App\Status', 'id_card', 'id_card')
->orderBy('status_date', 'desc');
}
对于状态表,我在状态模型中:
public function Card() {
return $this->hasOne('App\Card', 'id_card', 'id_card')
}
现在,我应该如何编写一个查询,它将返回卡片列表以及状态表中的值,但只有每张卡片的最新状态,如下所示:
id_card | card_type | status_type | status_date | status_company | status_user
--------|-----------|-------------|-------------|----------------|------------
123 | tag | lost | 2020-02-02 | |
281 | card | available | 2020-01-25 | |
455 | card | issued | 2020-02-14 | Company C | Third User
721 | tag | available | 2019-03-26 |
有没有办法过滤这样的查询,即只获取可用的卡片:
id_card | card_type | status_type | status_date | status_company | status_user
--------|-----------|-------------|-------------|----------------|------------
281 | card | available | 2020-01-25 | |
721 | tag | available | 2019-03-26 | |
非常感谢你:)
解决方案
获取所有具有 status_type 'available' 的卡片
Card::join('statuses', 'cards.id_card', '=', 'statuses.id_card')
->where('statuses.status_type', 'available')
->select('cards.id_card', 'cards.card_type', 'statuses.status_type', 'statuses.status_date', 'statuses.status_company', 'statuses.status_user')
->get();
要获得最新状态,您可以按照以下步骤操作,
- 在卡片模型中添加以下方法
public function latestStatus() { return $this->hasOne('\App\Status')->latest(); }
方法 latest() 按 desc 对所有行进行created_at
排序,并取第一行。如果您没有created_at
列,则可以将其添加到statuses
表中。
$cards = Card::with('latestStatus')->get();
foreach ($cards as $card) {
echo $card->type . ' has latest status of ' . $card->latestStatus->status_type;
}
最后但并非最不重要的一点是,我认为如果您遵循 laravel 约定,那么您已经解决了一半的问题。
推荐阅读
- r - 如何为另一列中的每个唯一值返回列的最大值?
- c++ - fastNlMeansDenoising 的 CUDA 版本与 CPU 版本不匹配?
- go - python“不返回”等价
- express - 使用 FeathersJS 看似限制性的 api 方法时如何组织端点?
- javascript - 如何在链接上使用 getElementById 来获取文本字段值
- reactjs - 同一自定义钩子的不同调用之间的数据泄漏(使用 useReducer)
- javascript - 嵌入一个外部小部件,但在加载正确的脚本之前它会以未定义的形式返回
- sql - 一对一映射 Spring boot
- python - Pyrfc 连接返回无
- google-apps-script - 生成额外空白行的 Google Apps 脚本函数