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 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写