问题描述
我有3张桌子
Users
-------------
user_id (PK)
user_name
Items_distributed
-------------
user_id (FK)
item_id(FK)
Item List
-----------------
item_id(PK)
item_name
现在我需要同时获取user_id和item_id并打印其item_name和user_name来打印Items_distributed表
Now i need to print Items_distributed table by taking both the user_id and item_id and dispaly their item_name and user_name
我不知道如何一次显示两者如果我显示item_name或user_name其工作但是当我尝试同时打印两者时,它不起作用.谁能解决我的问题.
i dont know how to display both things at a time if i display either item_name or user_name its working but when i try to print both it is not working .Can any one solve my problem .
这就是我打印值的方式
在控制器中,我像这样使用$itemdata=item::orderBy('user_id','desc')->paginate(10);
并在视野中我用
in controller i use like this $itemdata=item::orderBy('user_id','desc')->paginate(10);
and in view i use
@foreach($itemdata as $value)
<tr>
<td>{{$value->items->item_name}}</td>
<td>{{$value->users->user_name}}</td>
<td>{!!Html::link("editItem/",'Edit',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}
{!!Html::link("deleteItem/".$value->item_id,'Delete',array('class'=>'btn-sm btn-warning margin-left-btn'))!!}</td>
</tr>
@endforeach
推荐答案
您应使用Laravel雄辩关系.为数据库表创建模型文件时,只需将其与其他模型建立关系即可.
You should use Laravel Eloquent Relationship. When you create model file for DB Table, You just put relation with other model.
如果Relation已设置,则Laravel会从Related表中自动获取数据.
If Relation has set, than Laravel it self fetch data from Related table.
在您的情况下,将创建三个模型.
In your case, Three models are created.
1)用户模型.
2)项目模型.
3)ItemDestributed模型.
3) ItemDestributed Model.
UserModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model
{
/**
* Other code goes here
**/
public function itemDestribution()
{
return $this->hasMany('App\ItemDistribution','foreign_key');
}
}
ItemDestributionModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemDestribution extends Model
{
/**
* Other code goes here
**/
public function user()
{
return $this->belongsTo('App\User','foreign_key_of_user');
}
public function item()
{
return $this->belongsTo('App\Item','foreign_key_of_item');
}
}
您可以在此处中找到有关口才关系的更多信息.
You can find more about Eloquent Relation from Here.
这篇关于我如何在Laravel中显示带有两个外键的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!