dongwei1855 2013-10-23 06:45
浏览 11
已采纳

Laravel 4 Eloquent获取网站名称

I have two tables that are related by a foregin key:

Equipment Table

ID primary Site_ID foregin UnitNo Model

Site Table

ID Sitename

I want to show all the equipment from the equipment table but where is says site_id, I want to show the Site Name.

I am very new to laravel 4 and I am really stuck on how to produce this, my code is as follows:

<?php var_dump($equipment); ?>

@foreach($equipment as $item)
<ul>
    <li>{{$item->site_id}}</li>
    <li>{{$item->unitNo}}</li>
    <li>{{$item->Model}}</li>
</ul>
@endforeach

Controller:

<?php

class EquipmentController extends BaseController {

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{

    $equipment = equipment::all();


    return View::make('equipment.index', compact('equipment'));
}

Equipment Model

<?php
class Equipment extends Eloquent {
protected $guarded = array();

public static $rules = array();


public function site()
    {
        return $this->hasOne('site', 'site_id');
    }

}

Site Model

<?php

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

public static $rules = array();


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

}

I am completley lost at this point. Any help help would be apprciated

Thanks

  • 写回答

2条回答 默认 最新

  • dongshuogai2343 2013-10-23 16:06
    关注

    You'll only have to call $item->site->site_name. BUT for that, your Equipment Model has to belongsTo Site Model. Other way, it may not work.

    public function site()
        {
            return $this->belongsTo('Site');
    
        }
    }
    

    The site_id key already is on laravel's convention for foreing keys, so you don't need to explicity tell him that.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?