php - Laravel:如何将一个模型的一个变量传递给不同的查询以查看以及如何在视图中访问它
问题描述
我正在学习laravel。我一度感到困惑。
我有一个模型Trader
与其他两个模型具有一对一的关系,AgriculturalProduceMarketCommettee
并且CategoryMaster
.
traders
表有apmc_id
和category_id
作为外键。现在我想在一张表中显示traders_name
, 。apmc_branch_name
category_name
交易者模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Trader extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'traders';
// primary key
public $primaryKey = 'traders_id';
//timestamps
public $timestamps = true;
/**
* Attributes that should be mass-assignable.
*
* @var array
*/
protected $fillable = [
'apmc_id','category_id', 'traders_name', 'traders_address','traders_contact_number'
];
/**
* Get the apmc that has the trader.
*/
public function apmc()
{
return $this->belongsTo('App\AgriculturalProduceMarketCommettee', 'apmc_id');
}
/**
* Get the category that has the trader.
*/
public function categoryMaster()
{
return $this->belongsTo('App\CategoryMaster', 'category_id');
}
}
交易者控制器
public function index()
{
$traders = Trader::all();
$traderApmc = Trader::with('apmc')->get();
$traderCategory = Trader::with('categoryMaster')->get();
return view('traders.tradersDetails', compact('traders','traderApmc','traderCategory'));
}
tradesDetails.blade.php : 查看
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Trader Name</th>
<th>APMC Branch Name</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
@if(count($traders) >= 1)
@foreach ($traders as $trader)
<tr>
<td> {{$trader->traders_name}} </td>
<td> {{$traderApmc->apmc->apmc_branch_name}} </td>
<td> {{$traderCategory->categoryMaster->category_name}} </td>
</tr>
@endforeach
@else
<p>No records found!</p>
@endif
</tbody>
</table>
现在TraderController
,我正在'traders','traderApmc','traderCategory'
为一个模型传递 3 个不同的变量Trader
以查看tradersDetails
3 个不同的查询。但鉴于我使用这些变量的方式会给我收集实例的错误,例如
Facade\Ignition\Exceptions\ViewException
Property [apmc] does not exist on this collection instance.
我应该如何传递这些变量并在视图中访问它?请指导。提前致谢。
解决方案
而不是使用 3 个变量,您可以组合然后使用:
$trader = Trader::with(['apmc','categoryMaster'])->get();
传递给您的视图:
return view('traders.tradersDetails', compact('traders'));
你可以使用它你的观点:
@foreach ($traders as $trader)
<tr>
<td> {{$trader->traders_name}} </td>
<td> {{$trader->apmc->apmc_branch_name}} </td>
<td> {{$trader->categoryMaster->category_name}} </td>
</tr>
@endforeach
推荐阅读
- node.js - 正确的格式以在 Node Js 中发送错误并在 Angular 5 中使用它们
- sitecore - 我想将具有特定版本和特定语言的站点核心中的项目移动到另一个实例。我怎样才能做到这一点?
- javascript - 检测 javascriptinterface 方法是否存在
- assembly - 如何签署扩展mips(程序集)中程序参数中给出的二进制补码数
- python - TensorFlow 形状 (?,) 是什么意思?
- javascript - setTimeout() 是否在单独的线程上运行?
- video - 通过 id 随机访问视频帧
- ssl - Certbot-auto --manual 插件不起作用
- cmake - CMAKE:target_include_directories 和 include_directories
- java - java ObjectOutputStream方法的defaultWriteObject和writeObject的异同