Laravel: Sort Table Joined Using 'With' Clause - php

I'm using Laravel 4 and Eloquent ORM. I'm currently pulling records from my database using the following code:
public function index($type, $id)
{
$asset = Asset::where('public_id', '=', $id)
->with('attachments')
->with('attachments.attachment')
->with('tracks')
->with('tracks.track')
->where('locale', '=', Config::get('app.locale'))
->first();
return View::make('view-asset.index')
->with('asset', $asset)
->with('type', $type);
}
The table joined to this query using the with('tracks') statement has a column in it called track_order - I would like to be able to sort the rows returned by this part of the query by that column so that the tracks stored in the database are returned in the correct order.
Is it possible to do this and if so, how should I do it? So far I've tried something like this:
public function index($type, $id)
{
$asset = Asset::where('public_id', '=', $id)
->with('attachments')
->with('attachments.attachment')
->with('tracks')
->with('tracks.track')
->where('locale', '=', Config::get('app.locale'))
->orderBy('tracks.track_order', 'ASC')
->first();
return View::make('view-asset.index')
->with('asset', $asset)
->with('type', $type);
}
Which doesn't work and I can't figure out a way of doing this other than splitting things up into multiple queries.

You most certainly can:
with(['tracks' => function($query)
{
$query->orderBy('track_order', 'asc');
}])
Refer to Eager Loading Contraints in the documentation for more.

Related

Combine with Relation with where sentence in Laravel8

I'm learning Laravel's relations. I'm having problems with the 2nd line.
I would like to display records that Auth::user table's br_name column = Partner table's br_name column matches.
Could you teach me the right code please?
UPDATE
public function mybr()
{
$blogs = Blog::with('user','category','partner')
->where('App\Partner::partner()->br', Auth::user()->br_name)//I'm having problem this line
->where(function($query){
$query->where('status', '=','new');
->orWhere('status', '=', 'old');
})->paginate(250);
return view('blogs.mybr')->with('blogs',$blogs);
}
You could try the following code, and I have done some query refactoring too.
Like I have used whereIn
$blogs = Blog::with(['user','category','partner' => function ($query) {
$query->where('br', '=', Auth::user()->br_name);
}])->whereIn('status',['new','old'])
->paginate(250);

Get datas from relation table (with()) with a condition

I have an 'implementation' table that contains relationships to retrieve projects and scores.
The scores table contains a" user_id "field.
I would like to collect all the implementations but with only the score which contains the user_id.
My original query.
public function getImplementations($id, $student)
{
$data = Implementation::where('event_id', $id)->where('student_id', $student)->with('project', 'score')->get();
return response()->json($data);
}
My test for get only the score from specific user (only one score per user per implementation, so no conflict possible)
$data = Implementation::where('event_id', $id)
->where('student_id', $student)->with('project', 'score')
->whereHas('score', function ($query) {
$query->where('user_id', Auth::user()->id);
})->get();
But that does not give the expected result. This is not the right method and I do not know the right one.
Thanks for your help
I am not sure if there's a need to eager-load and constrain a relationship simultaneously. Does the following provide you with the expected result?
$data = Implementation::where('event_id', $id)
->with([
'project',
'score' => function ($query) {
$query->where('user_id', Auth::id());
}
])
->where('student_id', $student)
->get();

Want to call data from an array

public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo->company_name;
}
public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo['company_name'];
}
If i do that it shows --Undefined property also if i use return $jobsInfo['company_name'] now it shows blank page I know there is company_name index also i tried another index also. Why is it doing that?
Your main problem is not understanding what is returned by a paginate query. Have a good read of the docs for this https://laravel.com/docs/5.5/pagination#paginating-query-builder-results
That being said there are better ways of doing this with Laravel.
return Job::where('category_id', '=', $id)->select('company_name')->where('published', '=', 1)->get();
Will return a Collection of just company_name using the select function in the query builder.
https://laravel.com/docs/5.5/queries#selects

cant get the data I want from two different tables using Laravel

I have a table called instructor_class: user_id, class_id and I have another table classes: id, time, active.
I would like to show classes for a single user but only those classes that active is 0 or 1.
My current code looks like this:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
This code is displaying me everything, then I tried the following code:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
This again returns me same records, but of course the class property is null for each record, which at some point looks correct, but my point is if the 'active' field does not corresponds at the classes table do not show the record, seems like the where() stm within with() is optional..
I am kinda stuck here...
Would appreciate your help, opinions!
You can use ::has('classes') to only return the models that have related classes
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
Never thought it could be this simple:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();

Selecting and ordering data from a query using Laravel Eloquent

I am trying to use Laravel and eloquent to return results based on the following query.
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->orderBy('created_at', 'desc')
->paginate(5);
Ok, so that is fine, it return exactly what it should, all the blog posts with associated relations to other tables.
What I now want to do is return only the $blogPosts where a tag is clicked by the user. So let's say there is a tag "PHP", so I pass in that value as $tag to the method. I then have something like this.
public function tag_search($tag)
{
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->where('tags', $tag)
->orderBy('created_at', 'desc')
->paginate(5);
$categories = BlogCategories::with('blog_posts')->get();
$data = array('blogPosts' => $blogPosts, 'categories' => $categories,
);
return view('blog.index')->with($data);
}
Now my issue is actually relatively simple I guess, if the where clause was a column in the BlogPosts table it would work, I know this because I tried that.
However the above won't work as is, I can only use;
->where('x', y)
Where x is a field in the BlogPosts table. I want to return a set of values where the submitted $tag is the same as one associated to the tags attached to the blog posts.
Make sense? I think I am over thinking it the point I am just not thinking now :)
Add the column field 'tags' to your table and then these queries:
$blogPosts = BlogPosts::with('blog_user', 'blog_categories', 'blog_comments', 'tags')
->where('tags', '=', $tag)
->orderBy('created_at', 'desc')
->paginate(5);
$categories = BlogCategories::with('blog_posts')->get();
return view('blog.index', compact ('categories', 'blogposts'));
Ok so the answer was to use whereHas like this.
$blogPosts = BlogPosts::whereHas('tags', function ($query) use ($tag) {
$query->where('name', $tag);
})->orderBy('created_at', 'desc')
->paginate(5);
That returns a search based on the associated elements.

Categories