php - 索引页面不显示 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
解决方案
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);
}
你应该阅读并使用雄辩的关系。
推荐阅读
- java - 了解日期格式 2019-10-16 02:37:08.000+000
- java - 从 CSV 文件读取解析错误/问题
- marklogic - 如何安全地解耦 MarkLogic 集群?
- java - 有什么方法可以在没有身份验证的情况下将每个用户应用程序数据保存在 android 中
- python - 有没有办法在熊猫聚合函数中制作自定义函数?
- angular - 错误错误:未捕获(承诺):NullInjectorError:StaticInjectorError(Wr)[hm -> t]:
- sql-server - 将标量函数转换为表值函数以返回布尔值
- .htaccess - heroku 忽略 .htaccess 文件
- oracle - 从 Oracle XE 中删除整个数据,因为它已满
- kubernetes - Kubernetes AKS - 入口后端 404 错误