我正在尝试构建购物车,但没有显示购物车包含的内容。
这是错误的,这是我在控制器和刀片中的代码:
public function index()
{
$id = Auth::id();
$results = DB::table('carts')
->select('book_id')
->where('user_id', '=', $id)
->get();
$data = (array) $results;
$books = Book::all()->whereIn('id', $data);
return view('carts.index')->withBooks($books);
}
@foreach($books as $book)
<tr>
<td> {{ $book->autori }} </td>
<td> {{ $book->titulli }} </td>
<td> {{ $book->cmimi }}</td>
</tr>
@endforeach
答案 0 :(得分:1)
public function index()
{
$booksIds = DB::table('carts')
->select('book_id')
->where('user_id','=', Auth::id())
->get()
->pluck('book_id')
->toArray();
$books = Book::whereIn('id', $booksIds)->get();
return view('carts.index')->withBooks($books);
}
或使用单个查询:
public function index()
{
$books = Book::join('carts', static function($join) {
$join->on('books.id', '=', 'carts.book_id')
->where('carts.user_id', '=', Auth::id());
})->get();
return view('carts.index')->withBooks($books);
}
您应该阅读并使用eloquent relationships。