Agil
Agil

Reputation: 396

Category relationship is giving error when I try to acces category through post

When I try to access articles vie category it works properly here is category.php model

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

but when I try to access category name view article it doesn't work as it's supposed to, I made I mistake there and trying to fix it, but no luck so far. here is the Article model

public function category(){
    return $this->hasOne('App\category');
}

and there is a table for relation those two to each others it's called article_category in page where I get all articles for the given tag, I want to do something like $article->category->name there is something sound very wrong to me but I can't figure it out. The error I'm receiving is

Column not found: 1054 Unknown column 'category.article_id' in 'where clause' (SQL: select * from category where category.article_id = 1 and category.article_id is not null limit 1) (View: C:\wamp64\www\loremipsum\bluhbluhbluh\articleByTag.blade.php)

Btw the way I save the relationship for the article_category when an article is created is

$article->category()->sync($request->category, false);

Upvotes: 2

Views: 125

Answers (3)

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Relationships are not set correctly

Category model should be like :

 class Category extends Model 
 {

     protected $table='category';

    //give me all articles associated with the given category
    public function articles()
    {
        return $this->hasMany('App\Article');
    }
}

And Article model

class Article extends Model 
{
   protected $table='article';

   //get the category associated with the given article
   public function category()
   {
       return $this->belongsTo('App\Category');
   }
}

for attaching articles to a category:

$article->category()->associate($category)->save();

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You've said that article might have only one category. In this case, delete pivot table and add category_id into the articles table.

Then in the Article model define this relationship:

public function category()
{
    return $this->belongsTo(Category::class);
}

And in the Category model:

public function articles()
{
    return $this->hasMany(Article::class);
}

When you'll do that, you'll be able to access article's category with:

$article->category->name

Upvotes: 1

user320487
user320487

Reputation:

You have the relationship established incorrectly. Remove the intermediate table and add category_id to the articles table.

Upvotes: 1

Related Questions