亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢索帖子所屬類別的名稱

如何檢索帖子所屬類別的名稱

PHP
胡說叔叔 2021-12-03 14:40:27
我正在通過開發一個小博客來學習 Laravel,以了解框架及其提供的功能。我現在面臨的問題是“如何檢索帖子最初所屬的類別的名稱”我的帖子和類別之間的關系是多對多的。我有三張桌子PostCategoryCategoryPost我的帖子模型public function categories()    {        return $this->belongsToMany('App\category');    }我的類別模型public function posts()    {        return $this->belongsToMany('App\Post');    }除此之外,我還沒有制作任何數據透視表模型。我需要做嗎?我的數據透視表中的記錄如下:    id  category_id  post_id  ------  -----------  ---------     6            1         16     7            2         16     8            3         16     9            1         17    10            3         17    11            1         18    12            2         18我想顯示一個帖子最初所屬的當前類別的名稱,以便用戶可以在編輯頁面中添加或刪除類別。這些是我的遷移:郵政桌public function up()    {        Schema::create('posts', function (Blueprint $table) {            $table->increments('id');            $table->integer('user_id');            $table->Integer('status_id');            $table->string('title');            $table->text('body');            $table->text('media');            $table->string('tags');            $table->timestamps();        });    }分類表: public function up(){    Schema::create('categories', function (Blueprint $table) {        $table->increments('id');        $table->string('name');        $table->text('description');        $table->timestamps();    });}分類郵政表: public function up(){    Schema::create('category_post', function (Blueprint $table) {        $table->increments('id');        $table->integer('category_id');        $table->integer('post_id');        $table->timestamps();    });}
查看完整描述

1 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

編輯遷移:


分類郵政表

public function up()

{

    Schema::create('category_post', function (Blueprint $table) {

        $table->increments('id');

            $table->Integer('category_id')->unsigned();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

            $table->Integer('post_id')->unsigned();

            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

            $table->timestamps();

    });

}

然后在您的控制器中:


public function edit(Post $post) {

 $post=Post::with('categories')->find($post->id);

 $categories=Category::all(); 


 return view('admin.pages.post.edit',compact('post','categories')); }

在您的刀片中,您可以執行以下操作:


@foreach($post->categories as $category)

    {{ $category->name }}

@endforeach

這應該有效,但如果您有錯誤,請在此處提供。


查看完整回答
反對 回復 2021-12-03
  • 1 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號