Много-много отношений в контроллере - PullRequest
0 голосов
/ 21 ноября 2018

Я хочу, чтобы мой контроллер отправил список продуктов на мой взгляд, вот как я сейчас пытаюсь:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
} 

Wishlist.php

public function products()
{
    return $this->hasMany('App\Models\Product');
}

WishListsController.php

public function index()
{
    $wishList = WishList::find(1);
    $products = $wishList->products()->get();
    return view('WishLists.index',compact('products'));
}

Ошибка:

SQLSTATE[42S22]: Column not found: 1054 Champ 'products.wish_list_id' unknow in where clause (SQL: select * from `products` where `products`.`wish_list_id` = 1 and `products`.`wish_list_id` is not null)

Кажется, он ищет идентификатор в табличных продуктах, а не просматривает таблицу "многие ко многим"?Но я не могу найти почему.

1 Ответ

0 голосов
/ 21 ноября 2018

Product и WishList создают отношение Многие ко многим (по крайней мере для меня).В отношениях m---m метод belongsToMany() должен быть определен на обоих концах.

Если это предположение верно (схема отношений), определите ваши отношения следующим образом:

Product.php

public function wishLists()
{
    return $this->belongsToMany('App\Models\WishList');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\WishList', 'custom_table_name');
    */ 
}

WishList.php

public function products()
{
    return $this->belongsToMany('App\Models\Product');
    /**
    * if you have a pivot table with a diferent name than: 'product_wish_list'
    * use the second argument to indicate it:
    * return $this->belongsToMany('App\Models\Product', 'custom_table_name');
    */ 
}

Итак, теперь в вашем контроллере:

WishListController.php

public function index()
{
    $products = WishList::find(1)->products()->get();

    return view('WishLists.index', compact('products'));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...