简体   繁体   中英

Fetch Data From DB Using Defined Criteria in Laravel Eloquent

I have two databases named users and calls.

Calls table

<?php

public function up()
{
    Schema::create('calls', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->nullable();
        $table->timestamps();
        $table->text('terminal_id', 20);
        $table->text('terminal_name', 100);
        $table->text('fault_description');
        $table->string('call_status', 10)->default('New call');
        $table->string('pending_on', 20)->nullable();
        $table->text('closed_on', 20)->nullable();
        $table->text('closed_by', 50)->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

CallsController

public function index()
{
    $calls = Call::orderBy('created_at', 'desc')->get(); 

    return view('pages.newCall')->with('calls', $calls); 
}

public function viewCall($id) { 
    $calls = Call::find($id);

    return view('pages.viewCall')->with('calls', $calls);
}

Currently, the CallsController is returning all the rows in the calls table, but I want it to return only the rows that have the property 'New call' on the call_status column in the calls table. How do I do this from the CallsController?

If you want to get rows which have

1. call_status equal to 'New Call' :

$calls = Call::where('call_status', 'New call')->orderBy('created_at', 'desc')->get();

2. call_status not equal to 'New Call' :

$calls = Call::where('call_status', '<>', 'New call')->orderBy('created_at', 'desc')->get();

You could use != in place of <> above.

3. call_status equal to NULL (Empty) :

$calls = Call::whereNull('call_status')->orderBy('created_at', 'desc')->get();

4. call_status equal to 'New Call' or NULL :

$calls = Call::where('call_status', 'New call')->orWhereNull('call_status')->orderBy('created_at', 'desc')->get();

Laravel has an ORM which is Eloquent and it uses a query builder named as Fluent . For more on query building check official doc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM