索引页未显示db的对象,或有时显示未定义的变量

时间:2019-06-12 10:17:04

标签: php laravel

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

这是错误的,这是我在控制器和刀片中的代码:

    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

1 个答案:

答案 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