【问题标题】:Eloquent, pivot table data雄辩的,数据透视表数据
【发布时间】:2014-05-10 14:16:26
【问题描述】:

我得到了三个表例程,measurements 和 pools,它们的数据透视表是 measure_routine,它还存储了一个 pool_id,它引用 pools 表中的一个池。设置如下所示:

例程:

id
value
date
time
emp_id (To reference which employee conducted the task)

测量:

id
title

id
name

还有数据透视表measure_routine:

routine_id
measure_id
pool_id

到目前为止,我已经在我的模型中定义了:

例程.php

class Routine extends Eloquent
{
        public function measurements
        {
            return $this->belongsToMany('Measurement', 'measure_routine', 'routine_id', 'measure_id', 'pool_id')->withPivot('pool_id');
        }
    }

Measurement.php

class Measurement extends Eloquent
{
    public function routines()
    {
        return $this->belongsToMany('Routine', 'measure_routine')->withPivot('pool_id');
    }
}

池.php

class Pool extends Eloquent

{
    public function measurement_routine()
    {
        return $this->hasMany('measure_routine', 'pool_id');
    }
}

我想知道如何使用 eloquent 提取 pool_id(或者可能是台球表中的池名称)?

目前我已经尝试在控制器中使用 $data = Routine::has('measurements')->get() ,然后在视图中尝试 {{ $data->pivot->pool_id }} ,但是这导致试图获取非对象错误的属性。

【问题讨论】:

  • 如果您还没有完成,您可以为链接表创建模型。
  • 就像为 measure_routine 数据透视表创建模型一样?
  • 是的,您创建了一个模型RoutineHasMeasurements,假设这个模型与其他 3 个模型中的每一个都具有 hasMany 关系。现在您还可以检索池名称。

标签: php laravel eloquent


【解决方案1】:

您可以尝试这样的事情(从集合和枢轴中获取第一个项目):

$data = Routine::has('measurements')->get();
$data->first()->measurements->first()->pivot->pool_id;

因为$dataget() 返回的Routine 的集合,所以第一个项目有另一个measurements 的集合,所以再次从您可以使用first() 的集合中获取第一个measurements再次访问pivot->pool_id,因此您也可以在view 中使用循环,如下所示:

@foreach($data as $routine)
    {{ $routine->property }}
    @foreach($routine->measurements as $measurement)
        {{ $measurement->property }}
        {{ $measurement->pivot->property }}
    @endforeach

@endforeach

【讨论】:

  • 顺便说一句,你有没有机会知道我是如何提取池的名称而不是 ID 的?
  • 你必须在->withPivot('pool_id')之后添加->withPivot('pool_id')->withPivot('name'),另一个->withPivot
  • 如果你使用->withPivot('name'),那么你可以像pool_id一样访问->pivot->name
  • 当我添加第二个 withPivot 并尝试在 foreach 中使用 $measurement->pivot->name 访问它时,它似乎尝试选择 measure_routine.name。
  • 是的,它会显示measure_routine.name,因为withPivot 会在pivot 表中添加来自pools 的名称。
猜你喜欢
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多