duanjue6575 2014-03-31 09:36
浏览 22
已采纳

雄辩,数据透视表数据

I got three tables routines, measurements and pools, their pivot table is measure_routine which also stores a pool_id which references a pool in the pools table. The setup looks like such:

routines:

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

measurements:

id
title

pools

id
name

and the pivot table, measure_routine:

routine_id
measure_id
pool_id

Thus far I have defined in my models:

Routine.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');
    }
}

Pool.php

class Pool extends Eloquent

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

What I was wondering is how I would go about extracting the pool_id (or possibly the pool name from the pool table) using eloquent?

Currently I've tried using $data = Routine::has('measurements')->get() in the controller, and then trying {{ $data->pivot->pool_id }} in the view, but that resulted in a trying to get property of non-object error.

  • 写回答

1条回答 默认 最新

  • dongpo1216 2014-04-01 07:53
    关注

    You may try something like this (To get the first item from collection and pivot):

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

    Because, $data is a collection of Routine returned by get() so the first item has another collection of measurements, so again to get the first measurements from the collection you may use first() again and then access the pivot->pool_id, so you may also use a loop in your view as well, something like this:

    @foreach($data as $routine)
        {{ $routine->property }}
        @foreach($routine->measurements as $measurement)
            {{ $measurement->property }}
            {{ $measurement->pivot->property }}
        @endforeach
    
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据