Home > OS >  Many to many output on page
Many to many output on page

Time:10-28

I have a many-to-many relationship in the same model, this is how it looks

 public function articles()
    {
        return $this->belongsToMany('App\Models\Article', 'articles' , 'article_id' , 'article_recommended_id');
    }

    public function article_recommendations()
    {
        return $this->belongsToMany('App\Models\Article', 'article_recommendations' , 'article_id' , 'article_recommended_id');
    }

The question is how can I now display all this on the page php.blade

I am trying to do like this in a controller

$article_recommendations = Article::with(['article_recommendations' => function($query){
            $query->where('article_id', 1);
          }])->get();

And like this on the page itself

@foreach($article_recommendations as $article_recommend)
                    {{ $article_recommend->title }}
                @endforeach

But in the end I get all the articles that I have.

Schema::create('article_recommendations', function (Blueprint $table) {
            $table->unsignedBigInteger('article_recommended_id')->nullable();
            $table->foreign('article_recommended_id')
                ->references('id')->on('articles')->onDelete('set null');
            $table->unsignedBigInteger('article_id')->nullable();
            $table->foreign('article_id')
                ->references('id')->on('articles')->onDelete('cascade');
        });

CodePudding user response:

If you want to get only recommended articles, you need to organize your codes like this.

In Article model:

public function recommends()
{
    return $this->belongsToMany('App\Models\ArticleRecommend', 'recommends' , 'id' , 'article_id');
}

In my code I assume that you have a model named ArticleRecommend for your article_recommendations table.

In controller:

$article_recommendations = Article::whereHas('recommends')->get();

This code will only return you the recommended ones.

In blade:

@foreach($article_recommendations as $article_recommend)
    {{ $article_recommend->title }}
@endforeach

CodePudding user response:

Try something like this

$article = Article::with('article_recommendations')->find(1);

and then in blade you may loop like this

@foreach($article->article_recommendations as $article_recommend)
                {{ $article_recommend->title }}
@endforeach
  • Related