如何显示名称而不是id

时间:2015-09-29 12:37:50

标签: php laravel foreach

我有两个表:albumscategories

我正在我的索引页面中显示包含foreach的{​​{1}}循环的相册详细信息。

我想显示category_id而不是category_name

我正在使用Laravel

控制器代码..

category id

查看代码:

public function index() {
    $albums = Album::all();
    $categories = DB::table('albums')
        ->join('categories','albums.category_id','=','categories.id')
        ->select('*')->get();

    return view('admin.profile.index',compact('albums','categories'));
}

我想在第二个@foreach($albums as $album) <tr> <td>{{$album->album_name}}</td> <td>I want to diplay category_name here</td> <td>{{$album->created_at}}</td> <td> <input type="image" src="images/icn_edit.png" title="Edit"> <input type="image" src="images/icn_trash.png" title="Trash"> </td> </tr> @endforeach 代码中显示category_name

2 个答案:

答案 0 :(得分:3)

首先在模型中创建关系,然后执行以下步骤: -

Albums.php

foreach(var x in lookup)
{
    List<int> productList = x.ToList();
}

Categories.php

public function category()
    {
        return $this->belongsTo('Category', 'id');
    }

控制器

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

视图

public function index()
    {
        $albums = Album::all();

        return View::make('admin.profile.index', compact('albums'));
    }

答案 1 :(得分:0)

在控制器中添加列选择,如:

public function index()
    {
     $albums = Album::all();

$categories = DB::table('albums')
    ->join('categories','albums.category_id','=','categories.id')
    ->select('*,categories.category_name as cat_name')->get();
return view('admin.profile.index',compact('albums','categories'));

   }

查看代码:

  @foreach($albums as $album)
            <tr>

                <td>{{$album->album_name}}</td>
                <td>{{$album->cat_name}}</td>
                <td>{{$album->created_at}}</td>
                <td><input type="image" src="images/icn_edit.png" title="Edit"><input type="image" src="images/icn_trash.png" title="Trash">           </td>
            </tr>
                @endforeach