简体   繁体   中英

BadMethodCallException belongsToMany Laravel 5.4

Please i try to make a many to many relationship in Laravel 5.4 but i allways get this error:

BadMethodCallException in Builder.php line 2443: Call to undefined method Illuminate\\Database\\Query\\Builder::categories()

I think my code is fine , and i can't fix it , any help please.

THank you.

THis is my code :

User model

class User extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category', 'user_categorys');
    }

}

Category model

class Category extends Model
{

    public function users()
    {
        return $this->belongsToMany('App\User', 'user_categorys');
    }

}

Call method

$user = User::where('id',$id_user)->first();
            foreach ($request->input("idcategs") as $value) {
                $user->categories()->save($value);
            }

You should use attach() , detach() and sync() methods when using many to many relationship to attach or detach models.

If idcategs is an array of IDs, do something like:

$user = User::find($id_user);
$user->attach($request->idcategs);

If it's an array of prepared data, you'll need to create categories first:

$categoriesIds = [];
$user = User::find($id_user);
foreach ($request->idcategs as $value) {
    $categoriesIds[] = Category::create($value)->id;
}
$user->attach($categoriesIds);

https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

You get it wrong: If you have a Many to Many relationship one or your relation should be:

public function users()
    {
        return $this->belongsToMany('App\User', 'foreign_key');
    }

and you will have to define a pivot table category_user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM