Use Pivot Table to Fetch Data from Main Table - laravel

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?

Related

How do I search by a table included using with() statement

I am trying to search with a column on a connected table using with. According to laravel the following should work.
$lineItems = Invoice::with(['invoiceHeader' => function ($query) {
$query->where('community_id', '=', 1);
}, 'invoiceLineItems'])
->limit(10)
->get()
->toArray();
However, I don't get anything from the invoiceHeader table and I get all the invoices available. If I take out the function I get the same but with invoiceHeader's table values showing up.
$lineItems = Invoice::with(['invoiceHeader', 'invoiceLineItems'])
->limit(10)
->get()
->toArray();
It seems I might be doing something of a right join where I get all the Invoices but then only the invoiceHeader values when applicable to the foreign key.
Edit:
I put ->toSql(); after the limit() and it shows I only get the following.
"select * from `invoice` limit 10"
You should use whereHas mixing with with:
$lineItems = Invoice::with(['invoiceHeader', 'invoiceLineItems'])
->whereHas('invoiceHeader', function ($query) {
return $query->where('community_id', 1);
})
->limit(10)
->get()
->toArray();

Join Laravel tables

I have got three tables Kudos, Kudoscategories, and specialpost. I need to get the data from those tables and check the post id using a where condition.
I have attached the database table screenshot here
I already tried this, but it's not getting any result.
$results = DB::table('kudos')
->select('kudos.description','kudoscategory.catname','kudoscategory.image','kudos.spid')
->join('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
What I need to do is get the results using below where condition newsfeed_special_posts.main_post_id = kudos.spid
You must add another join with newsfeed_special_posts.
The query will be like,
$results = DB::table('kudos')
->select('kudos.description','kudoscategory.catname','kudoscategory.image','kudos.spid')
->join('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->join('newsfeed_special_posts', 'newsfeed_special_posts.main_post_id', '=', 'kudos.spid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
Though this is not a good practice for laravel. using laravel eloquent relationships will be more efficient for these results.
https://laravel.com/docs/5.8/eloquent-relationships
you can still do it this way. still efficient to avoid sql injection since you are getting all the record from the 3 tables. seeing your table above, its not properly normalised. anywaye try this.
$results = DB::table('kudos')
->leftjoin('kudoscategory', 'kudoscategory.id', '=', 'kudos.categoryid')
->leftjoin('newsfeed_special_posts', 'newsfeed_special_posts.id', '=', 'kudos.spid')
->where('kudos.spid', '=', $post_id)
->first();
return $results;
you can try this code
at first, create model Kudos,KudosCategory,NewsfeedSpecialPosts
Kudos Model
public function kudoscategory_dta()
{
return $this->belongsTo('App\Model\KudosCategory','categoryid');
}
public function newsfeed_special_posts_dta()
{
return $this->belongsTo('App\Model\NewsfeedSpecialPosts','spid','main_post_id ');
}
controller
Kudos::with('kudoscategory_dta','newsfeed_special_posts_dta')->first();

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

Laravel Query Builder left join

can someone please tell me, why i am not able to select section from sections table using left join. i want list of teachers in a table, i am able to access all data from teachers table, but i am not able to see sections using left join.
Teacher Table have section_id column, which should access data from sections table on section column.
right now it is giving error when i try to fetch data in view using {{$teacher->section}} Below is my code.
public function listteachers(Request $request)
{
$teachers = DB::table('teachers')
->select('teachers.*')
->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
return view('teachers.list',compact('teachers'));
}
You need to select the columns you want from the sections table in your query.
For example:
$teachers = DB::table('teachers')
->select('teachers.*', DB::raw('sections.name as section_name'))
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
Change the code to the following
$teachers = DB::table('teachers')
->select('teachers.*','sections.name as section_name')
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();

Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

I have the following relationship functions in my Job model:
public function resourceTypes(){
return $this->belongsToMany('ResourceType', 'job_requests');
}
public function resources(){
return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');
}
I am able to get an object with data from both of the above relationships using:
$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();
I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.
How would I do this?
Try something like this:
$job = Job::with('resources' => function($q) {
$q->with('resourceTypes')->where('flow_type',2);
})->findorfail($projectId);
In above you will get only those resources with flow_type = 2
I ended up using the following statement:
Job::with(['resources' => function ($query){
$query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
$result = DB::table('job')
->join('job_resources', 'job.id', '=', 'job_resources.job_id')
->join('job_requests', 'job_resources.request_id', '=', 'job_requests.id')
->where('job_resources.flow_type', '=', CONDITION)
->get();
Your table data is not clear from your input, but this method (query builder) should work

Resources