【发布时间】:2021-09-20 12:20:21
【问题描述】:
我正在开发一个 API,它负责获取购物车(列)值等于 1 的(记录)数据,如何实现这件事请帮助我
这就是我遇到错误的原因
Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'bookstore.books.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from `books` group by `cart` having `cart` > 0) in file C:\xampp\htdocs\laravel-bookstore\vendor\laravel\framework\src\Illuminate\Database\Connection.php
FileController.php
public function cartItem(){
$books=Books::all();
if(User::find($books->user_id=auth()->id())->books){
$users=DB::table('books')->groupBy('cart')->having('cart','>',0)->get();
// $users=DB::table('books')->whereIn('cart',[1])->get();
return response()->json(['books'=>$users],200);
}
}
Books_Migration_Table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('author');
$table->integer('price');
$table->integer('quantity');
$table->string('file')->nullable();
$table->longText('description');
$table->unsignedBigInteger('user_id');
$table->enum('cart', [0, 1])->default(0);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
【问题讨论】:
-
如果您想要一组特定的值,为什么要使用 groupby?
Book::whereIn('cart', [1])->get()应该够了 -
感谢您的评论@MuaRachmann。我这样写,return Books::whereIn('cart', [0])->get();...它在我的邮递员中显示一个空数组..