简体   繁体   中英

Laravel 4: Query to Eloquent

I have a query builder that works like this:

$query = DB::table($tablename);

if($keyword!=""){
    $query->where($field,'like','%'.$keyword.'%');
}

$query->get();

How can I convert it into eloquent?

Thank you,

You can simply do this:

In your model make a query scope like:

//code to be written in your model  

public function scopeGetdata($field,$keyword){

      return  $query->where($field,'like','%'.$keyword.'%');

}

Let say our model name is Custom . Now use this as follows:

Custom::Getdata($fieldname,$keyword)->get();

Read this to Explore more!!

Create a model extending Eloquent

class MyModel extends Eloquent {
           protected $table = 'MyTableName';
}

Then use query builder like

MyModel::where($field,'like','%'.$keyword.'%')->get();

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