首页 > 解决方案 > 索引页面不显示 db 的对象或有时显示未定义的变量

问题描述

我正在尝试构建一个购物车,但它没有显示购物车包含的内容。

这里有问题是我在控制器和刀片中的代码:

    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

标签: phplaravel

解决方案


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);
}

你应该阅读并使用雄辩的关系


推荐阅读