首页 > 解决方案 > 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  |                |

非常感谢你:)

标签: sqllaravel

解决方案


获取所有具有 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 约定,那么您已经解决了一半的问题。


推荐阅读