mercredi 26 février 2020

Laravel how to manage many to many relationship for FAQs

I am working on adding FAQs in database using laravel 5.6 many to many relationship. Here are my migrations:

Faq Category: (List of all the types of FAQs)

Schema::create('faq_categories', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->softDeletes();
                $table->timestamps();
            });

Faq Table:

 Schema::create('faqs', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title', 160);
                $table->longText('description');
                $table->boolean('published')->default(0);
                $table->softDeletes();
                $table->timestamps();
            });

Faq Types: (All the FAQs categories for particular FAQ)

Schema::create('faq_types', function (Blueprint $table) {
               $table->increments('id');
                $table->integer('faq_id')->unsigned();
                $table->foreign('faq_id')->references('id')->on('faqs')->onDelete('cascade');
                $table->integer('faq_category_id')->unsigned();
                $table->foreign('faq_category_id')->references('id')->on('faq_categories')->onDelete('cascade');
                $table->timestamps();
            });

I have defined relationship like this:

App\FaqCategory

class FaqCategory extends Model {

    use SoftDeletes;

    public function faqs() {
        return $this->belongsToMany('App\Faq');
    }
}

App\Faq

class Faq extends Model {

    use SoftDeletes;

    public function categories() {
        return $this->belongsToMany('App\FaqCategory');
    }

}

I want all the FAQs by their category. Suppose there General, Other category in faq_categories table then I want faqs grouped by General, Other.

But I am not able to retrieve all faqs grouped by category. I did following but facing error:

$faq = FaqCategory::find(1);
        return $faq->faqs;
        dd($faq);

Error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_name.faq_faq_category' doesn't exist.

Can anyone suggest me how to deal with this situation or best way to handle this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire