SELECT school_courses.*, schools.school_name, schools.country, schools.city FROM
school_courses JOIN schools ON school_courses.school_id = schools.id
Hello there,
I want to convert the above SQL query to laravel.
And also I want to learn joins in laravel query please share any easy step by step tutorial link if you have one.
This is Query Builder way of doing it.
$result = DB::table('school_courses')
->join('schools','schools.id','=','school_courses.school_id')
->select('school_courses.*','schools.school_name', 'schools.country', 'schools.city')
->get();
Refer this link https://laravel.com/docs/8.x/queries#joins
My suggestion is to use better Eloquent: Relationships
Relationships
Your converted query is given below
use Illuminate\Support\Facades\DB;
$users = DB::table('school_courses')
->join('schools', 'us schools ers.id', '=', 'contacts.user_id')
->select('school_courses.*','schools.school_name', 'schools.country', 'schools.city')
->get();
Related
I just want to know what type of SQL join is happening in the following view. I read about types of SQL joins but I am not able to figure out what is happening here.
class WishListItemsView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = WishListItemsCreateSerializer
def get_queryset(self):
user = self.request.user
return WishListItems.objects.filter(owner=user)
My models:
class WishListItems(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE,blank=True)
#wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems')
item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
wish_variants = models.ForeignKey(Variants,on_delete=models.CASCADE, related_name='wishitems')
I can see it in Django debug toolbar, but it is authenticated so I cant see the queries.
No joins are happening in your code. The following line is the queryset you return:
WishListItems.objects.filter(owner=user)
This filtering does not need any joins, Django will simply use the SQL WHERE clause to make this filter. Suppose the primary key of the user here is 1, then the query would be somewhat like:
SELECT <ALL OF YOUR TABLES COLUMNS HERE> FROM "<APP_NAME>_wishlistitems" WHERE "<APP_NAME>_wishlistitems"."owner_id" = 1
You can see the exact query by writing:
print(WishListItems.objects.filter(owner=user).query)
Moving further if you do want to make some join for optimizing or speeding up things use select_related [Django docs] which will make Django use an INNER JOIN:
WishListItems.objects.filter(owner=user).select_related('owner', 'item') # select the related owner and item
i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image
result
and here my sql code in postgresql
select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc
how to fix this query where i got the multiple data only 1 data to show.
and i want this sql to implement to laravel query and here my code now
public function getAccountList(){
$req = app(Request::class);
// $getAccount = User::query();
$getAccount = User::join('model_has_roles', function($join) {
$join->on('users.id', '=', 'model_has_roles.model_id');
})->leftJoin('roles', function($join){
$join->on('model_has_roles.role_id', '=', 'roles.id');
});
$getAccount->whereNotIn('roles.name', ['job-seeker']);
if ($q = $req->query('q')) {
$searchTerm = trim(strtolower($q));
$getAccount->whereRaw(
'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
["%{$searchTerm}%", "%{$searchTerm}%"]
);
}
// $getAccount->get()->unique('name');
$getAccount->select(['users.*']);
$paginator = $this->pagination($getAccount);
return $this->paginate($paginator, new UserTransformer);
}
how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You
use distinct()
$data = DB::table('test')->[your query builder]->distinct()->get();
Laravel Query Builder Docs
Just change a bit to make it related to your query builder
I have orm query like tthis:
$userCountries = ORM::factory('User')
->select(array(DB::expr('countries.code, COUNT("countries.id") as total')))
->join('countries')
->on('user.country_id', '=', 'countries.id')
->group_by('country.name')
->order_by('total', 'DESC')
->find_all();
What i want is country code with total users quantity from country.
I do not know what is wrong here. I spent 3 hours on it with no success.
What is wrong with this query?
Your SELECT Params is wrong
->select('countries.code', array(DB::expr('COUNT("countries.id")', 'total')))
I think the Group by should be
->group_by('countries.name') instead of ->group_by('country.name')
So Your Total Query will look like
$userCountries = ORM::factory('User')
->select('countries.code', array(DB::expr('COUNT("countries.id")', 'total')))
->join('countries')
->on('user.country_id', '=', 'countries.id')
->group_by('countries.name')
->order_by('total', 'DESC')
->find_all();`
Check this out...
I am new to entity framework and learning making queries. Can anyone please help me how can I convert the following SQL query to run in entity framework?
select max(isnull(TInvoice.InvoiceNr, 0)) + 1
from TInvoice inner join TOrders
on TInvoice.OrderId = TOrders.OrderId
where TOrders.ClientFirmId = 1
As comments have said, without the data model it is hard to be exact.
Would really need to see how you have defined your relations in your data model.
I guess from first read my first impression is something along the lines of:
int max = context.TInvoice.Where(x => x.TOrders.ClientFirmId == 1).Max(x => x.InvoiceNr);
how to write the sql bellow to django model sql language ?
select id,author_id from forum_node as answer_node where node_type='answer' and
'android' in (select tagnames from forum_node as question_node where
id=answer_node.parent_id );
could any one give help
Hard to say exactly without seeing you model classes, but selecting the relevant Forum_Node objects will look something like this:
Forum_Node.objects.filter(
node_type="answer",
parent__tagnames__name__in=['android']
)
Or, to get just the id and author_id:
Forum_Node.objects.filter(
node_type="answer",
parent__tagnames__name__in=['android']
).values_list('id', 'author_id')