我有 2 個表,資產和歷史。在表 phhistories 中將帶有 asset_id。我想顯示所選資產 ID 下的歷史記錄串列。到目前為止我在 AssetController 中嘗試過的:
public function edit(Asset $asset)
{
$phistories = (DB::table('phistories')->where('asset_id',$asset)->get());
return view('assets.editAsset',[
'asset' => $asset,
'phistories' => $phistories
]);
}
這是我的觀點
@foreach($phistories as $phistory)
<tr>
<td>{{$phistory->id}}</td>
<td><a href="/edit/{{$phistory->id}}/editPhistory"><span>{{$phistory->phistory_name}}</span></a>
</td>
<td>{{$phistory->phistory_category}}</td>
<td>{{$phistory->phistory_pic}}</td>
</tr>
@endforeach
我的問題是它沒有在視圖中顯示任何內容。任何人都可以檢查我的查詢是否正確或我使用了錯誤的方法?
uj5u.com熱心網友回復:
假設您有一個名為 Assets 和 Phistories 的模型,您需要在這些模型中撰寫多對多關系。IE
在您的資產模型中,添加此功能;
public function phistories()
{
return $this->belongsToMany(Phistories::class);
}
定義關系后,您可以使用phistories資產控制器中的動態關系屬性訪問歷史記錄:
use App\Models\Assets;
public function edit(Asset $asset)
{
$assets = Assets::with('phistories');
return view('assets.editAsset',['assets' => $assets]);
}
如果您希望能夠從 Phistories 模型訪問資產,請使用此選項
在您的 Phhistories 模型中,添加此關系;
public function Assets()
{
return $this->belongsToMany(Assets::class);
}
現在,在您的視圖中,您可以像這樣訪問 Phistory 資料,
@foreach($assets as $asset)
<tr>
<td>{{$asset->id}}</td>
@foreach($asset->phistories as $phistory)
<td>
<a href="/edit/{{$phistory->id}}/editPhistory">
<span>{{$phistory->phistory_name}}</span>
</a>
</td>
@endforeach
</tr>
@endforeach
uj5u.com熱心網友回復:
$phistories = (DB::table('phistories')->where('asset_id',$asset)->get());
改變
$phistories = (DB::table('phistories')->wherein('asset_id',$asset)->get());
如果 $asset 是多個 ID
其次請嘗試 first() 插入 get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352664.html
下一篇:如何將電子郵件發送到多個地址?
