duanji9264 2014-05-27 16:02
浏览 56
已采纳

Laravel资源:: all包含来自另一个表的值

I'm learning Laravel right now and i have following tables and resources (models, controllers, ect.):

tickets
- id
- title
- projectID
- statusID

projects
- id
- title

status
- id
- title

I have to make a list of my Tickets on the Startpage. Not nessesary to say that i need the Project- and Statustiltles and not the IDs. Currently i do:

Route::get('/', function()
{
    $tickets = Ticket::all();
    return View::make('layout')->with('tickets', $tickets);
});

My current output is:

tickets->id, tickets->title, tickets->projectID, tickets->statusID

The output i want is

tickets->id, tickets->title, tickets->projects->title, tickets->status->title

So i hope anyone can understand what i'm trying to ask here and maybe provide me some help. Thank you!


Resolution: I had to set the foreign_keys first in my DB. Then i used the relationships mentioned in the answers and it works fine.

My Model:

class Ticket extends \Eloquent {
    protected $fillable = [];

    public function project()
    {
        return $this->hasOne('Project', 'id', 'projectID');
    }

    public function status()
    {
        return $this->hasOne('Status', 'id', 'statusID');
    }
}

My View:

@foreach($tickets as $key => $value)
...
  <td>{{ $value->project->title }}</td>
  <td>{{ $value->status->title }}</td>
...
@endforeach
  • 写回答

2条回答 默认 最新

  • douduiwei2831 2014-05-27 16:16
    关注

    If you configure you relationships correctly you can do that without problems using the Laravel Eager Loading feature, for example:


    Eager Loading (Laravel docs)

    Eager loading exists to alleviate the N + 1 query problem...

    class Ticket extends Eloquent {
    
        public function project()
        {
            return $this->belongsTo('Project', 'projectID', 'id');
        }
    
        public function status()
        {
            return $this->belongsTo('Status', 'statusID', 'id');
        }
    
    }
    

    Now, just call the fields you want, for example:

    foreach (Ticket::all() as $ticket)
    {
        echo $ticket->project->title;
        echo $ticket->status->title;
    }
    

    Obs.: In your return object/array you can't see the relationships fields unless you do manual joins, etc. So, just configure your relationships and call the fields you want.

    Sorry for my english

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?