1 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
好的,我將在這里做出一些假設(shè),但假設(shè)您的設(shè)計(jì)模型上有這個(gè)函數(shù):
設(shè)計(jì).php
class Design extends Model
{
...
/**
* Assuming you dont have a slug column on your designs table
*
* Also assuming the slug is built from a column called 'name' on
* your designs table
*/
public function getSlugAttribute()
{
return \Illuminate\Support\Str::slug($this->name);
}
// This assumes there is a column on posts table of 'design_id'
public function posts()
return $this->hasMany(Post::class);
}
...
}
現(xiàn)在讓我們舉例說明如何構(gòu)建所需的路線。
編輯
通過與提問者進(jìn)一步討論,他們不想顯示與他們所展示的設(shè)計(jì)相關(guān)的所有帖子(參見上面的模型)。這個(gè)答案中的設(shè)置適合于此,您可以參考下面定義的 show 方法。假設(shè)我們有DesignsController.php:
class DesignsController extends Controller
{
...
public function index()
{
return view('designs.index', [
'designs' => Design::all(),
]);
}
public function show(Request $request, string $design)
{
// It is worth noting here if name has a double space you wont
// be able to build backwards to it for a query
// ie) Design\s\sOne !== $lower(Design\sOne)\
$spaced = str_replace('-', ' ', $design);
$lower = strtolower($spaced);
$design = Design::with('posts')->whereRaw("LOWER(name) = '$lower'")->first();
return view('designs.show', [
'design' => $design,
]);
}
...
}
現(xiàn)在,在“designs/index.blade.php”文件中,您可以執(zhí)行以下操作:
@foreach($designs as $design)
<a href="{{ route('designs.show', [ 'design' => $design->slug ]) }}">{{ $design->name }}</a>
@endforeach
這將按名稱列出您的所有設(shè)計(jì),并通過其 slug 鏈接到 designs.show 路線。
如果您始終希望在序列化為數(shù)組或 json時(shí)加載 slug 值,則可以將其添加到模型上受保護(hù)的 $appends 數(shù)組中。
如果您不總是希望附加它,則需要在運(yùn)行時(shí)使用例如$design->append('slug').
或者,如果您有一系列設(shè)計(jì),您也可以這樣做$designs->each->append('slug')。
現(xiàn)在,在您的 designs.show Blade 文件中,您可以使用我們使用 Design::with('posts') 加載的關(guān)系訪問設(shè)計(jì)的帖子,方法如下:
@foreach ($design->posts as $post)
<img src="{{ asset('storage/'.$post->postImage) }}">
@endforeach
- 1 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報(bào)