I have read the documentation but I can't quite figure out how to run the following query in Laravel 4
SELECT
COUNT(*)
FROM
acl a,
routes r
WHERE
(a.user_id = 1 OR
a.group_id IN(SELECT group_id FROM user_group_junction WHERE user_id = 1)) AND
r.route = 'protected' AND
a.routes_id = r.id;
So how would I run the query in Laravel 4 using eloquent?
Yes each table has a model and relationships are defined
Based on my selected answer the following is what I came up with (And works)
Acls::join('routes','routes.id','=','acl.routes_id')
->where('routes.route','=','protected')
->Where(function($in_parenthesis) use($user_id){
$in_parenthesis->whereIn('acl.group_id',function($where_in) use($user_id){
$where_in->select('group_id')
->from('user_group_junction')
->where('user_id','=',$user_id);
})
->orWhere('acl.user_id','=',$user_id);
})
->count();
Methods called on Eloquent models pass through to the Illuminate\Database\Eloquent\Builder class, which itself extends from the Illuminate\Database\Query\Builder class. This means that all the things you can do with the query builder, you can also do with Eloquent models. The exception being that you don't need to define the table.
So for example if you wanted to perform a join and a where like you've done above, you would just do:
$query = Acl::join('routes', 'acl.routes_id', '=', 'routes.id')
->where('routes.route', '=', 'protected');
$results = $query->get();
Obviously this isn't your whole query, but you can figure out the rest.
Related
This is my query, I tried this query it works.
SELECT *
FROM conference_venue
WHERE id_venue NOT IN (SELECT id_venue FROM submission_data WHERE id_submission = 1);
i want to display data in conference_venue. but I don't want to display data whose id_venue is the same as the submission_data table (same as id_venue whose id_submission is mentioned).
I'm trying to make a query for the laravel version, but it's a blank white screen with no errors.
DB::table('conference_venue')
->whereNotIn('id_venue', function($q){
$q->select('id_venue')
->from('submission_data')
->where('id_submission', '=', 1);
})->select('*')->get();
This query works when I try it in sql query console but fails when I try it with Laravel query builder.
You can try this:
DB::table('conference_venue')
->select('*')
->whereRaw(
'conference_venue.id_venue NOT IN (SELECT submission_data.id_venue FROM submission_data WHERE id_submission = 1)'
);
Or better yet, create a Model for conference_venue and submission_data (ie: ConferenceVenue, SubmissionData) and you can add Eloquent relationships for ConferenceVenue and SubmissionData.
Eloquent relationships, which supports a variety of common
relationships (One To One, One To Many, Many To Many, etc.), are
defined as methods on your Eloquent model classes. Since relationships
also serve as powerful query builders, defining relationships as
methods provides powerful method chaining and querying capabilities.
Eloquent: Relationships
On you ConferenceVenue Class, you can add a method something similar to the following:
public function available() {
return this->hasMany(SubmissionData, 'id_venue')
->select('*') // You can also specify relevant columns ONLY
->whereRaw(
'conference_venue.id_venue NOT IN (SELECT submission_data.id_venue FROM submission_data WHERE id_submission = 1)'
);
}
Where you can use the relationship method as follows:
$available = ConferenceVenue::with('available')->get();
hello I am new to laravel and maybe I am a bit confused between eloquent and query builder way for writing a query but anyway can you please tell me what could be the best eloquent way to retrieve info like this in laravel 6 or 7
User > hasMany > Recipes
Recipe > belongsTo > User
I want to check if user id 2 present in users table then get only one post which id is 3
Query builder is for explicitly building SQL queries, and does not return instances of your models. Eloquent query builder, is similar but the result will contain the model(s) loaded with all their attributes, and has some handy functions for querying the relations you define in your models.
Given the limited information in your post, I am assuming when you say a post, you mean a recipe:
Query Builder:
DB::table('users')
->join('recipes', 'recipes.user_id', '=', 'users.id')
->select(['users.some_col', ... 'recipes.some_col'])
->where('users.id', 2)
->get();
If you have your models setup with the relations. You can use Eloquent like so:
User::where('id', 2)->with('recipes')->get();
If I understand you correctly it would be like this:
User::whereId($userId) //asuming it is 2
->with(['recipes' => function($q) use($recipeId) {
$q->where('id', $recipeId); //assuming it is 3
}])->first();
you can do this if i understand correctly:
$user = User::findOrFail(2); //auto 404 if user not found
$recipe = $user->Recipes()->where('id',3)->first();
You may use conditional eager loading for better performance.
$userId = 2;
$receiptId = 3;
$user = User::with(['receipts'=> function ($query) use($receiptId){
$query->where('id', $receiptId);
}
])->find($userId)
I am bit struggling to convert below given SQL query to eloquent.
Here is an example of what I am trying to do -
SELECT u.wallet_address AS wallet_address, p.id AS project_id
FROM users u, projects p, investment_investor i
WHERE u.id = i.user_id AND
p.id=i.project_id AND
u.wallet_address <> '' AND
p.wallet_address <> '' AND
p.contract_address <> ''
GROUP BY u.id, p.id;
The below SQL query gives me the expected output, which I am able to build with the Laravel DB query builder. But want to standardise it to Laravel framework.
Your help is much appreciated!
First thing you need to have to be able to write queries in the laravel way is something called Model. Example of a model would be like so
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
You can read more about it here
Once you create it, you can start writing queries. For example
$results = Users::selectRaw('users.wallet_address as `wallet_address`,'.
'id as `project_id`')
->get();
You can read more about joins and other things here
$result=DB::table('investment_investor')
->select('users.wallet_address as wallet_address','projects.id AS project_id')
->join('users','users.id','=','investment_investor.user_id')
->join('projects','projects.id','=','investment_investor.project_id')
->where('users.wallet_address','!=','')
->where('projects.wallet_address','!=','')
->where('projects.contract_address','!=,'')
->groupBy('users.id', 'projects.id')
->get();
How am using laravel 5.4,
to write sql query to get data from multiple tables for below query
select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5
Now am using this
Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();
but it is getting too confuse to use
is there any better alternative to use this query by using model..
You would have to join the tables to do this.
Containerlease::join('tbl_partys', 'tbl_partys.id', '=', 'tbl_container_lease.party_id')
->where('tbl_container_lease.user_id', 5)
->select('tbl_partys.*', 'tbl_container_lease.*');
->get();
However, an even better way would be to create relations if you are using Eloquent. The documentation for this can be found here: https://laravel.com/docs/5.4/eloquent-relationships
It would be better, since you're in laravel after all, to make use of laravel relationships.
Make sure you have a party model:
php artisan make:model Party
Assuming one lease has one party, In your container lease model add:
public function party(){
return $this->hasOne('App\Party', 'id', 'party_id');
}
Then access your model
ContainerLease::with('party')->where('user_id', '=', 5)->get();
Laravel Framework - using version 5.4: If I used raw query as shown below in User.php controller and making paginate(3) as shown below. But it is giving error as "Call to a member function paginate() on array". solution please.
DB::select("select u.email,u.name,u.created_at from users u where u.id in (select max(ui.id) from users ui where ui.status = 0) order by ui.id desc")->paginate(3);
This code will do the job
DB::table('users as u')->select(['u.email','u.name','u.created_at'])->whereRaw("u.id in (select max(ui.id) from users ui where ui.status = 0)")->orderBy("ui.id","desc")->paginate(3);
yeah because your query ain't returning an object its returning an array. Try to use laravel query builder or Eloquent.
$users = DB::table('users')->paginate(15); //query builder example
$users = User::where('votes', '>', 100)->paginate(15); //eloquent example
Also make sure your query is working fine.