Laravel口才:对两个表中的数据进行计数

问题描述 投票:0回答:2

我有两个不同的表,分别命名为artistsartworks。我想从两个表中检索数据并将它们显示在Summary表中。

这里的条件是:从name表中获取artists(此表中还有其他列),并从number of total artworks表中获取artworks。在Summary表中显示它们。

artists
|-------------------|
|  id   |   name    |
|-------------------|
|  1    |    A      |
|-------------------|
|  2    |    B      |
|-------------------|
|  3    |    C      |
|-------------------|

artworks
|-----------------------------------------------------|
|  id   |   artist_id   |   title   |     medium      |
|-----------------------------------------------------|
|  1    |       1       |    ABC    |      Oil        |
|-----------------------------------------------------|
|  2    |       1       |    DEF    |     Water       |
|-----------------------------------------------------|
|  3    |       1       |    GHI    |     Water       |
|-----------------------------------------------------|
|  1    |       2       |    JKL    |      Oil        |
|-----------------------------------------------------|
|  2    |       2       |    MNO    |     Water       |
|-----------------------------------------------------|
|  3    |       3       |    PQR    |      Oil        |
|-----------------------------------------------------|

这就是我想要的:

Summary
|-------------------------------------------|
|  No   |   Artist Name  |   Total Artwork  |
|-------------------------------------------|
|  1    |        A       |         3        |
|-------------------------------------------|
|  2    |        B       |         2        |
|-------------------------------------------|
|  3    |        C       |         1        |
|-------------------------------------------|

任何帮助将不胜感激。谢谢您的时间。

mysql laravel eloquent laravel-5.7
2个回答
2
投票

由于要使用数据库查询,因此需要添加联接。

\DB::table('artists')
->join('artworks', 'artists.id', '=', 'artworks.artist_id')
->select('artists.id as id', 'artists.name as name', \DB::raw("count(artworks.artist_id) as count"))
->groupBy('artists.id')
->get();

如果您要使用关系,请在艺术家模型中使用hasMany关系。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Artist extends Model
{
    protected $table = 'artists';

    public function artworks()
    {
        return $this->hasMany('App\Artwork','artist_id','id');
    }
}

在控制器中

$artists = Artist::withCount('artworks')->get();
foreach($artists as $artist) {
    echo $artist->artworks_count;
}

3
投票

您可以在关系上使用withCount()方法:

$artists = Artist::withCount('artworks')->get();
foreach($artists as $artist) {
    echo $artist->artworks_count;
}
© www.soinside.com 2019 - 2024. All rights reserved.