When using eloquent single table query like this
$query = Lists::query();
we can save in a temporary variable, but when we use multiple tables like this
Lists::with(['tags','keyproduct','productcatalog']);
why can't we save it in a variable like above? The reason I want to store in a temp variable like this is because I wanted conditional statement in the query like
if($something==true)
$query->where('type'=>'Paid')
Any idea how to break down the query using ::with()?
you can give condition in whrehas
$posts = List::whereHas('comments', function($q)
{
if($something==true){
$q->where('content', 'like', 'foo%');
}
})->get();
For more details http://laravel.com/docs/5.0/eloquent#querying-relations
Related
I want to use if else in a query but using the data of this query using where clause
If you want to conditionally eager load a realtionship, you can use when(condition, callback) in your query.
$query = YourModel::query()
->when($something == true, function ($query) {
$query->with('relationship')
})
please someone can optimize this query according to Laravel query builder with some help of joins
Product::select(DB::raw('
products.*
,(select name from users where users.id=products.user_id) as user_name
'))
->where(function ($query) use ($searchKey) {
if (trim($searchKey) != '') {
$query->where('name', 'like', '%' . trim($searchKey) . '%');
}
})
->orderBy($orderBy,$orderType)
->paginate(10)
Maybe something like this:
//Start your query as usual, but just join the user data in. Do not use paginate function yet as this will trigger the query to execute.
$productQuery = Product
::selectRaw('products.*, users.name as user_name')
->join('users', 'users.id', 'products.user_id')
->orderBy($orderBy, $orderType);
//Check (for each param) if you want to add where clause
//You dont need to nest the where function, unless you have more filters, and need to group statements together
if(!empty(trim($searchKey))) {
$productQuery->where('name', 'like', '%' . trim($searchKey) . '%');
}
//Execute query
$products = $productQuery->paginate(10);
Note that the query builder only touches the db with specific functions like chunk, get, first or paginate(there are more). When building the query, you have full freedom of adding filters/ordering/grouping untill you execute the query.
I hope it helps, please let me know if it worked for you.
I have this code
$users = array();
$users_to_add = User::all()->where('unit', 'LIKE', '%'.$request->unit.'%');
But i get nothing on $users_to_add. The like doesn't work. What am i missing?
all() actually runs a query to get all users. Therefore, your where() call is on the Collection (PHP), not the Query Builder (SQL).
You'll want to use get() but make sure you declare your query conditions prior to calling it.
get() will execute the query, with your defined conditions, and return a collection of results.
User::where('unit', 'LIKE', '%'.$request->unit.'%')->get();
Im using a simple query to pull the users in a table called users.
$users = DB::table('users')->get();
Then using a foreach loop to get the values , for example :
foreach ($users as $user)
{
return $user->email;
}
There is definitely 2 records in the DB Table, but it only returns one line. If i try to query a different table it does the same thing.
If i use the Query Log between the query
DB::enableQueryLog();
$users = DB::table('users')->get();
$result = DB::getQueryLog();
It returns the query and it looks fine
[{"query":"select * from `users`","bindings":[],"time":0.85}]
This table was created within PhpMyAdmin and not using the Artisan Migrate
Of course it so, cause you return from loop, use echo
foreach ($users as $user)
{
echo $user->email;
}
return statement inside the loop will behave like break for your case, this means breaking the loop.
You can use either:
DB::table('users')->select(['email'])->get();
or
DB::table('users')->get(['email']);
But its basics, you can easily find this stuff in docs https://laravel.com/docs/master/
I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)