简体   繁体   中英

Laravel Eloquent ORM and Conditional Statements

I am trying to use Laravel's Eloquent ORM with conditional statements for example, in Codeigniter I can use the following syntax to filter my database results;

<?php
      $this->db->select('*')->from('demos'); 

      if (isset($data) && is_numeric($data) ) 
      {
         $this->db->where('type_id', $data);
      } 

      if (isset($name) && is_string($name) ) 
      {
         $this->db->where('name', $name);
      }

      return $this->db->get(); ?>

I have tried the same implementation which doesn't seem to work; how do I replicate the above using Eloquent?

Thanks for your assistance

Try the following, if you have your models set up:

$demos = Demo::query();
if (isset($data) && is_numeric($data) )
{
    $demos->where('type_id', $data);
}
if (isset($name) && is_string($name) )
{
    $demos->where('name', $name);
}

return $demos->get();

Thanks for the suggestion, @JofryHS. Code updated accordingly.

Since you did not provide any information about Models, you can use Query Builder instead of Eloquent.

$data = Input::get('data', null);
$types = DB::table('demos')->where('type_id', '=', $data)->get();

and for the second part

$name = Input::get('name', null);
$names = DB::table('demos')->where('name', '=', $name)->get();

you can also short it to just

$data = Input::get('data');
$types = DB::table('demos')->whereData($data)->get();

$name = Input::get('name');
$names = DB::table('demos')->whereName($name)->get();

EDIT

Following the comment, I figured out that the query should be connected.

$data = Input::get('data');
$name = Input::get('name');
$result = DB::table('demos')
             ->where('type_id', $data)
             ->whereName($name)
             ->get();

In newer versions of Laravel (5.2.27 and up) you can actually do something similar to:

$results = DB::table('orders')
->when($request->customer_id, function($query) use ($request){
    return $query->where('customer_id', $request->customer_id);
})
->get();

Hope that will help for newcomers

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