【问题标题】:How to write a database query to fetch all records whose column value is 1 in laravel-8?如何编写数据库查询以获取 laravel-8 中列值为 1 的所有记录?
【发布时间】: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])-&gt;get() 应该够了
  • 感谢您的评论@MuaRachmann。我这样写,return Books::whereIn('cart', [0])->get();...它在我的邮递员中显示一个空数组..

标签: mysql laravel laravel-8


【解决方案1】:

只需使用 whereIn 即可获得所需的输出

 return  Books::whereIn('cart', ['1'])->get();

我希望这能解决您的问题

【讨论】:

    【解决方案2】:

    试试这个

        $books_record = DB::table('books')->where(['cart', '=', '1'])->get();
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2016-07-08
      • 2017-02-28
      相关资源
      最近更新 更多