【问题标题】:how to show labels in laravel charts when the name of the label is on another table?当标签的名称在另一个表上时,如何在 laravel 图表中显示标签?
【发布时间】:2019-12-23 23:26:21
【问题描述】:

我有一张许可表

    Schema::create('permits', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('application_id')->unique();
        $table->string('type_id')->nullable();
        $table->integer('state_id')->nullable();

它和我的状态表是一对一的关系

    Schema::create('states', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');

我想在我的视图中制作一个图表。在我的控制器中,我正在计算按 state_id 分组的许可证数量

    $data = Permit::all()->groupBy('state_id')->map(function ($item) {
        return count($item);
    });

在为图表制作标签时,我只能传递 id 而不能传递名称,这是我的图表所需要的。

    $chart = new PermitsChart;
    $chart->labels($data->keys());

谁能帮忙...

【问题讨论】:

  • 您是要按州或相反的方式打印许可证数量吗?另外,如果您有 1:1 的关系,那么每个州的许可计数将始终为 0 或 1,对吗?你说只能打印id不能打印名字,是指州名吗?
  • 我只能显示 id 而不是该 state_id 的名称。我不知道如何将两者联系起来

标签: laravel eloquent chart.js relationship


【解决方案1】:

假设您设置了 Permit 和 State 模型之间的关系,并且您想计算每个州的许可数量(所以我认为您的意思是 1:N 关系),您可以这样做:

$data = State::withCount('permits')->all();

// Then when you need to extract data
$chart = new PermitsChart;
$chart->labels($data->pluck('name'));

// To retrive the permit_count foreach state you can to
$data->pluck('permits_count'); // Array of counts

更新
要设置模型之间的关系,您必须添加:

Permit.php

class Permit extends Model
{
    // Your existing code
    public function state()
    {
        return $this->belongsTo(State::class);
    }
}

State.php

class State extends Model
{
    // Your existing code
    public function permits()
    {
        return $this->hasMany(Permit::class);
    }
}

【讨论】:

  • 那么别忘了将答案标记为正确! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
相关资源
最近更新 更多