Getting the name of the foreign key with eloquent

北慕城南 提交于 2019-12-06 09:43:44

Assuming you have set up your schema correctly: armies table has at least id(auto-increment) and units table has at least id(auto-increment) and army_id (integer, unsigned), then, try this:

Models

class Army extends Eloquent {
   public function units()
   {
     return $this->hasMany('Unit');
   }
}


class Unit extends Eloquent {
  public function armies()
  {
    return $this->belongsTo('Army');
  }
}

In your Controller You want to get all armies with units:

$armies = Army::with('units')->get();

In your View you want to loop through the result set outputting the name of each army and its respective units

@foreach($armies as $army)
    {{$army->name}}
       <ul>
          @foreach($army->units as $aunit)
            <li>        
               {{ $aunit->name }}
            </li>
          @endforeach
       </ul>
@endforeach

If that doesn't work, I'll eat my head.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!