Elaine Marley
Elaine Marley

Reputation: 2233

Getting the name of the foreign key with eloquent

This must be very basic stuff but I can't seem to find out how to do it.

I have a one to many relationship between to tables: Unit and Army (an army contains many units) and these are my models:

class Army extends Eloquent {
    protected $guarded = array();

    public static $armies = array();

    protected $table = 'armies';

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

}

and:

class Unit extends Eloquent {
    protected $guarded = array();

    public static $units = array();

    protected $table = 'units';

    public function armies()
    {
        return $this->belongsTo('Army', 'army');
    }


}

So, in my Unit table I have a row called"army" that contains the id of the army related to that unit and I want to show in my view a simple ul list in the following fashion (I want this to show on the unit index view):

 <ul>
      <li>Army 1 name
           <li>Unit 1 of Army 1</li>
           <li>Unit 2 of Army 1</li>
      </li>
      <li>Army 2 name
           <li>Unit 1 of Army 2</li>
           <li>Unit 2 of Army 2</li>
      </li>
 </ul>

To do this I have my unit controller like so:

class UnitsController extends BaseController {

protected $layout = 'master';

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{
    $units = Unit::all();

    $this->layout->content = View::make('units.index', compact('units'));


}
/*Other stuff*/
}

And in my view (index.blade.php inside views/units):

<ul class="units">
    @foreach($units as $unit)
        {{$unit->army}}
            <li>        
        {{ HTML::link(route('units.show', ['units' => $unit->id]), $unit->name)}}
    </li>
@endforeach
</ul>

But {{$unit->army}} is just (of course) showing the id of the army, and I want the name, how do I do this?

Upvotes: 2

Views: 7788

Answers (1)

kJamesy
kJamesy

Reputation: 6243

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.

Upvotes: 3

Related Questions