Adding Multiple Where Clause from Model in Laravel - laravel

I am trying to clean my code up, and working on the Models
I have the following 2 tables broken down like this:
Roll Table
|id|roll_id|member_id|.......
Members table
|id|first_name|last_name|rank|
I have the following on my Roll Model
public function member()
{
return $this->belongsTo('App\Member');
}
This on my Member model
public function roll()
{
return $this->hasMany('App\Roll');
}
While the following code does return the correct results
$roll = Roll::with(['member'])
->where('status', '!=', 'A')
->get();
return ($roll);
I would like to add an extra where clause
->where('rank','<', 12)
However, I get the following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'member.rank'
in 'where clause' (SQL: select * from Roll where roll_id = 4 and
status != A and `mem ▶"

You can use whereHas method to filter on the relations:
$roll = Roll::with(['member'])
->where('status', '!=', 'A')
->whereHas('member', function($query) {
$query->where('members.rank', '<', 12);
})
->get();
Hope this will resolve your issue.

Related

SQLSTATE 42S22 Column not found

I know that I don't have the table in phpmyadmin
but the problem is I don't know how to do it the right way
The code
public function DriverRefer($id)
{
$driver = Driver::find($id);
$query = ReferralDiscount::where([['referral_driver_id', '=', $id], ['referral_sender_id', '!=', 0]])->latest();
$referral_details = $query->paginate(25);
return view('merchant.driver.driver_refer', compact('referral_details', 'driver'));
}
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'referral_driver_id' in 'where clause' (SQL: select count(*) as aggregate from referral_discounts where (referral_driver_id = 4130 and referral_sender_id != 0))
Previous exceptions
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'referral_driver_id' in 'where clause' (42S22)
I added a model inside App/Models named DriverReferralDiscount:
<?php
class DriverReferralDiscount extends Model
{
protected $guarded = [];
public function Driver()
{
return $this->belongsTo(Driver::class, 'referral_driver_id');
}
public function SenderDriver()
{
return $this->belongsTo(Driver::class, 'referral_sender_id');
}
public function getSenderDetails($driver_id)
{
$refer = ReferralDiscount::where([['referral_driver_id', '=', $driver_id], ['referral_sender_id', '!=', 0]])->get();
return $refer;
}
public function getSenderCount($driver_id)
{
$refer = ReferralDiscount::where([['referral_driver_id', '=', $driver_id], ['referral_sender_id', '!=', 0]])->count();
return $refer;
}}
And changed the code to
public function DriverRefer($id){
$driver = Driver::find($id);
$query = DriverReferralDiscount::where([['referral_driver_id', '=', $id], ['referral_sender_id', '!=', 0]])->latest();
$referral_details = $query->paginate(25);
return view('merchant.driver.driver_refer', compact('referral_details', 'driver'));}
Then i added a table in phpmyadmin named driver_referral_discounts with columns:
id
referral_driver_id
referral_sender_id
referral_offer
referral_offer_value
referral_available
created_at
updated_at
Really sorry if it's not clear but i tried as best as i could in case this would help anyone else.

How to fix Laravel query builder where clause integer variable translated to string

I have a function to get a pass a language number to get language categories record for API purpose. I use a database query statement to select categories table and join the category language table to get category id, parent_id and name (specified language). When execute return error and select the underlying SQL converted the language value to string (e.g. languages_id = 1). I google a lot and no ideas what's wrong. Can anyone advise how to resolve. Thanks a lot.
I tried to copy the underlying SQL to MySQL Workbench and remove the languages_id = 1 --> languages_id = 1 can working properly. I guess the 1 caused error.
Code Sample:
private function getCategories($language) {
$categories = DB::table('categories')
->select(DB::raw('categories.id, categories.parent_id, categories_translation.name'))
->join('categories_translation', function($join) use ($language) {
$join->on('categories_translation.categories_id', '=', 'categories.id');
$join->on('categories_translation.languages_id', '=', $language);
})
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id]
])
->get();
return $categories;
}
Error return the converted SQL:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on
clause' (SQL: select categories.id, categories.parent_id,
categories_translation.name from categories inner join
categories_translation on categories_translation.categories_id =
categories.id and categories_translation.languages_id = 1
where (parent_id = 0 and categories.id = 1))"
You are trying to join using a comparison to an scalar value, instead of a column. I think you actually want to put that comparison as a "where" condition, rather than a "join on"
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id],
['categories_translation.languages_id', '=', $language]
])
there is another thing i just discover with your code. when joining table, you are suppose to be joining 'categories_translation.languages_id' with another table id field. in your case, it is not so. you are not joining 'categories_translation.languages_id' with any table field. so ideally, what you are going to do is this
private function getCategories($language) {
$categories = DB::table('categories')
->select(DB::raw('categories.id, categories.parent_id, categories_translation.name'))
->join('categories_translation', function($join) use ($language) {
$join->on('categories_translation.categories_id', '=', 'categories.id');
})
->where([
['parent_id' ,'=', '0'],
['categories.id', '=', $id]
['categories_translation.languages_id', '=', $language]
])
->get();
return $categories;
}
hope this helps

Use Pivot Table to Fetch Data from Main Table

I am using two tables and a pivot table
Table 1 named calendars.
Table 2 named calendar_groups.
Pivot table calendar_calendar_group.
I'm trying to get data from Table 1 based on a where value in the pivot table. Where calendar_groups_id = 1 then use calendar_id to get data from table 1. I can't get it to work.
$event = new Calendar();
$event->orderBy('start', 'asc')
->whereHas('calendar_groups', function ($q) {
$q->wherePivot('calendar_groups_id', '=', '1');
})->with('calendar_groups')
->first();
This gives me the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in
'where clause'
This is the relationship:
public function calendar_groups()
{
return $this->belongsToMany(CalendarGroup::class);
}
Your help is very much appreciated.
I think #Tpojka is right here. If you're trying to get Calendar instances that belong to desired CalendarGroup then replace the code should look like this:
$event = new Calendar();
$group = 1;
$event->orderBy('start', 'asc')
->whereHas('calendar_groups', function ($q) use ($group) {
//$q->wherePivot('calendar_groups_id', '=', $group);
$q->where('id', '=', $group);
})->with('calendar_groups')
->first();
If I'm reading the documentation correctly wherePivot() should be used like this:
$event = new Calendar();
$event->calendar_groups()->wherePivot('some_pivot_column',1)->get();
But this would return you the CalendarGroup instances.
If you'd want to do it through Eloquent but without going all the way to the CalendarGroup then you'd probably need to create a Model (let's call it CalendarCalendarGroupPivot) for the pivot table and add another relation (hasMany('CalendarCalendarGroupPivot')) to your Calendar model.
Ok finally got it working.
I used your suggestions but still don't understand a little part of it.
When I use the suggestions made:
$event = new Calendar;
$event->orderBy('start', 'asc')
->whereHas('calendar_groups', function($q) {
$q->where('calendar_group_id', '=', '1');
})->with('calendar_groups')
->first();
I get an empty collection.
But if I run this:
$event = Calendar::orderBy('start', 'asc')
->whereHas('calendar_groups', function($q) {
$q->where('calendar_group_id', '=', '1');
})->with('calendar_groups')
->first();
I get the desired results
Can anybody tell me the difference between so I can learn from it?

Laravel Repositories whereHas -- multiple

I have the following repository Products and each product can have many Categories and many Bidders
What I am trying to achieve is the following (Without Repository)
$products = Products::whereHas('categories', function ($category) {
})->whereHas('bidders', function ($bidder) {
})->get();
This works fine, however, I am trying to make it so that repositories are in place and you can still do the whereHas query, so in my repository I created a method:
public function whereHas($attribute, \Closure $closure = null)
{
return $this->model->whereHas($attribute, $closure);
}
This works well, but only if I am using one of them in my main query, whereas if I use multiple:
$products = $this->products->whereHas('categories', function ($category) {
$category->where('id', '=', 1);
})->whereHas('bidders', function($bidders) {
})->get();
I am getting the following error:
Unknown column 'has_relation'
Column not found: 1054 Unknown column 'has_relation' in 'where
clause' (SQL: select * from products where exists (select * from
categories inner join products_categories on categories.id =
products_categories.categories_id where products.id =
products_categories.products_id and id = 1) and (has_relation
= sections))
The issue I'm seeing is that its returning a collection of items on the first whereHas which means it cannot compute the second one. Any ideas to where I am going wrong?
You can pass a closure with multiple relations to whereHas
$products = $this->products->whereHas(['categories', function
($category) {
$category->where('id', '=', 1);
},'bidders' => function($bidders) {
}])->get();
It will work as expected.

How to use query scope in join request Laravel?

I have the following request:
$objects = Object::with("translate")->where(function ($query) use ($request) {
$query->language();
})->with('images')->with("category")->orderBy('id', 'desc')->paginate($limit);
So, in model Object there is method: translate:
public function translate()
{
return $this->hasMany("App\ObjectTranslate", "objectId", "id");
}
So, also in this model is:
public function scopeLanguage($query)
{
$languageHeader = new ModelLibrary();
return $query->where('language', '=', $languageHeader->getLanguage());
}
When I try to call scope in main request:
$query->language();
I get SQL error:
Column not found: 1054 Unknown column 'language' in 'where clause' (SQL:
You need to join the query with ObjectTranslate's table. your scopeLanguage() function will not work , since you are trying to access the column language which is not available in Object model column.
Note : With() will just eager loading, which will load the eloquent defined function, you cannot directly access their column in where clause.
Modify your scopeLanguage function
public function scopeLanguage($query)
{
$languageHeader = new ModelLibrary();
return $query->join('object_translate_table','object_translate_table.objectId','=','object_table.id')->where('object_translate_table.language',$languageHeader->getLanguage());
}
$objects = Object::with("translate","images","category")
->language()
->orderBy('id', 'desc')
->paginate($limit);
This should work
Assumin ObjectTranslate model's table name is object_translate_table and Object model's table name is object_table

Resources