How to get the name of an ID from other table [LARAVEL] - php

This query that I did is to fetch service_id and its count in ServiceOrder model:
$test = DB::table('serviceorders')
->select('serviceorders.service_id', DB::raw('COUNT(services.id) AS count'))
->join('services', 'serviceorders.service_id', '=', 'services.id')
->groupBy('serviceorders.service_id')
->whereMonth('serviceorders.created_at',Carbon::now("Asia/Kuala_Lumpur")->month)
->get();
I have no idea how to fetch the name of an id since it is at another model
Here's the result when I dd($test)
as you can see, it displays service_id because yeah I typed that but I don't know how to fetch the serviceName . also this way of query can be difficult if I'm trying to display it in a pie chart using chartJs (correct me if it is easy)
these are the tables involved
I am also looking for a right way to do this.

Here you go using Eloquent functions:
ServiceOrder::withCount('services')
->whereMonth('created_at', today()->month)
->having('services_count', '>', 0) // this is optional if you wish to avoid orders with 0 services
->get();
// now you will have this attribute `services_count`
// NOTE: Adjust your Carbon timezone within your `config/app.php` timezone to be 'Asia/Kuala_Lumpur'
It might not work if you don't have a relation (function) called services() within your ServiceOrder model, and for sure I guessed that this is your model name :) let me know if it was different so I can help out.

Related

Laravel mysql select result

I am trying to add a feature to a website built with Laravel.
There is a table containing vote numbers and user. I want to get the total points a user has in a certain category. I do not have any PHP or Laravel experience but said I would give this a shot.
$votes1 = UserVotes::select ('select vote from user_votes where feedback_id = ? and feedback_type = 1', Auth::user()->id);
This should return an object containing the vote amount. I want to interrogate the the object to check if the vote number is above a certain amount and then do something based on that being the case or not.
if vote > 50{
//do stuff
}
foreach ($votes1 as $vote1) {
echo $vote1->vote;
}
The query should return 1. I have verified this by querying the database, so the problem is with my understanding of Laravel or php. What I am doing wrong?
You don't need to construct your own SQL statement; Eloquent will do that for you.
If your models are set up in the default way, your query would look something like:
$votes = UserVotes::where('feedback_id', Auth::user()->id)
->where('feedback_type', 1)
->get();
You can then iterate over that as normal.
Additionally, if there is a relationship set up with the user model you could do something like
$votes = Auth::user()->votes()
->where('feedback_type', 1)
->get();
Check out the documentation here: http://laravel.com/docs/4.2/eloquent
assuming UsersVotes extends Model, here's how you should do it:
UsersVotes::select('vote')->where('feedback_type', 1)->where('feedback_id', Auth::user()->id)-get();

Laravel Restful Controller ID

So to explain my issue, whenever i am connecting to the database with Laravel it will default search for the id column as "id".
If i name my column jobID for example, i would like to controller to search for "jobID" instead of just "id". I could just change all of my tables ID columns to "id" however this causes issues when you use Laravel's left joins as it will take the latest id column as the actual id column.
Heres my join:
$jobs = Job::leftJoin('occupational_areas', function($join) {
$join->on('jobs.occupationalArea', '=', 'occupational_areas.id');
})->get();
However Restful controller default to "id" and that is what i'm asking, how do i change the default "id" to becomes something more custom like jobID
Try using this left join
$jobs = Job::select('occupational_areas.id as occ_id', 'jobs.id as jobs_id', your required values)
->leftJoin('occupational_areas', 'jobs.occupationalArea', '=', 'occupational_areas.id')
->get();
comment for errors
Turns out the easiest way to do this is by setting:
protected $primaryKey = 'jobID';
Into your model.
I am pretty sure Ronser also had it right with his method. Either will work.
Thanks Ronser!

Laravel 4 - Eloquent way to attach a where clause to a relationship when building a collection

This may be a dupe but I've been trawling for some time looking for a proper answer to this and haven't found one yet.
So essentially all I want to do is join two tables and attach a where condition to the entire collection based on a field from the joined table.
So lets say I have two tables:
users:
-id
-name
-email
-password
-etc
user_addresses:
-address_line1
-address_line2
-town
-city
-etc
For the sake of argument (realising this may not be the best example) - lets assume a user can have multiple address entries. Now, laravel/eloquent gives us a nice way of wrapping up conditions on a collection in the form of scopes, so we'll use one of them to define the filter.
So, if I want to get all the users with an address in smallville, I may create a scope and relationships as follows:
Users.php (model)
class users extends Eloquent{
public function addresses(){
return $this->belongsToMany('Address');
}
public function scopeSmallvilleResidents($query){
return $query->join('user_addresses', function($join) {
$join->on('user.id', '=', 'user_addresses.user_id');
})->where('user_addresses.town', '=', 'Smallville');
}
}
This works but its a bit ugly and it messes up my eloquent objects, since I no longer have a nice dynamic attribute containing users addresses, everything is just crammed into the user object.
I have tried various other things to get this to work, for example using a closure on the relationship looked promising:
//this just filters at the point of attaching the relationship so will display all users but only pull in the address where it matches
User::with(array('Addresses' => function($query){
$query->where('town', '=', 'Smallville');
}));
//This doesnt work at all
User::with('Addresses')->where('user_addresses.town', '=', 'Smallville');
So is there an 'Eloquent' way of applying where clauses to relationships in a way that filters the main collection and keeps my eloquent objects in tact? Or have I like so many others been spoiled by the elegant syntax of Eloquent to the point where I'm asking too much?
Note: I am aware that you can usually get round this by defining relationships in the other direction (e.g. accessing the address table first) but this is not always ideal and not what i am asking.
Thanks in advance for any help.
At this point, there is no means by which you can filter primary model based on a constraint in the related models.
That means, you can't get only Users who have user_address.town = 'Smallwille' in one swipe.
Personally I hope that this will get implemented soon because I can see a lot of people asking for it (including myself here).
The current workaround is messy, but it works:
$products = array();
$categories = Category::where('type', 'fruit')->get();
foreach($categories as $category)
{
$products = array_merge($products, $category->products);
}
return $products;
As stated in the question there is a way to filter the adresses first and then use eager loading to load the related users object. As so:
$addressFilter = Addresses::with('Users')->where('town', $keyword)->first();
$users= $addressFilter->users;
of course bind with belongsTo in the model.
///* And in case anyone reading wants to also use pre-filtered Users data you can pass a closure to the 'with'
$usersFilter = Addresses::with(array('Users' => function($query) use ($keyword){
$query->where('somefield', $keyword);
}))->where('town', $keyword)->first();
$myUsers = $usersFilter->users;

Laravel ORM "with" is returning all rows even with constraint

Using Laravel 4 Eloquent ORM, any idea why the following is pulling every row instead of just the one I'm asking for (book_id=3)?
if ($Book = Book::find(3)) {
return (Book::with(array('chapters.pages' => function($query)
{
$query->where('book_id', '=', 3 ); // hard-coded id for illustration purposes
})
)->get()->toJson());
}
The output I'm getting is every single book with every chapter and every page. I only want to pull that single book with chapters and pages.
According to the documentation I should be able to add a constraint. Seems like I'm following the docs pretty closely. Thanks in advance.
I think the problem is you are asking for Book::with() - but you have not put a constraint on the Book() itself. So you need to do Book::with()->where()
Does this work
Book::with(array('chapters.pages' => function($query)
{
$query->where('book_id', '=', 3 ); // hard-coded id for illustration purposes
})
)->where('id', '=', '3')->get()->toJson());
note the ->where() - which is putting the id constraint on the query.
Edit: if you have correctly defined relationships (such as HasMany() etc) - then this should work:
$books = Book::with('chapters.pages')->where('id', '=', '3')->get();
Because the relationship with mean it only gets the 'chapters/pages' for the book with id of 3 by defintion.

Laravel Eloquent: How to get only certain columns from joined tables

I have got 2 joined tables in Eloquent namely themes and users.
theme model:
public function user() {
return $this->belongs_to('User');
}
user model:
public function themes() {
return $this->has_many('Theme');
}
My Eloquent api call looks as below:
return Response::eloquent(Theme::with('user')->get());
Which returns all columns from theme (that's fine), and all columns from user (not fine). I only need the 'username' column from the user model, how can I limit the query to that?
Change your model to specify what columns you want selected:
public function user() {
return $this->belongs_to('User')->select(array('id', 'username'));
}
And don't forget to include the column you're joining on.
For Laravel >= 5.2
Use the ->pluck() method
$roles = DB::table('roles')->pluck('title');
If you would like to retrieve an array containing the values of a single column, you may use the pluck method
For Laravel <= 5.1
Use the ->lists() method
$roles = DB::table('roles')->lists('title');
This method will return an array of role titles. You may also specify a custom key column for the returned array:
You can supply an array of fields in the get parameter like so:
return Response::eloquent(Theme::with('user')->get(array('user.username'));
UPDATE (for Laravel 5.2)
From the docs, you can do this:
$response = DB::table('themes')
->select('themes.*', 'users.username')
->join('users', 'users.id', '=', 'themes.user_id')
->get();
I know, you ask for Eloquent but you can do it with Fluent Query Builder
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->get(array('themes.*', 'users.username'));
This is how i do it
$posts = Post::with(['category' => function($query){
$query->select('id', 'name');
}])->get();
First answer by user2317976 did not work for me, i am using laravel 5.1
Using with pagination
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->select('themes.*', 'users.username')
->paginate(6);
Another option is to make use of the $hidden property on the model to hide the columns you don't want to display. You can define this property on the fly or set defaults on your model.
public static $hidden = array('password');
Now the users password will be hidden when you return the JSON response.
You can also set it on the fly in a similar manner.
User::$hidden = array('password');
user2317976 has introduced a great static way of selecting related tables' columns.
Here is a dynamic trick I've found so you can get whatever you want when using the model:
return Response::eloquent(Theme::with(array('user' => function ($q) {
$q->addSelect(array('id','username'))
}))->get();
I just found this trick also works well with load() too. This is very convenient.
$queriedTheme->load(array('user'=>function($q){$q->addSelect(..)});
Make sure you also include target table's key otherwise it won't be able to find it.
This Way:
Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
I know that this is an old question, but if you are building an API, as the author of the question does, use output transformers to perform such tasks.
Transofrmer is a layer between your actual database query result and a controller. It allows to easily control and modify what is going to be output to a user or an API consumer.
I recommend Fractal as a solid foundation of your output transformation layer. You can read the documentation here.
In Laravel 4 you can hide certain fields from being returned by adding the following in your model.
protected $hidden = array('password','secret_field');
http://laravel.com/docs/eloquent#converting-to-arrays-or-json
On Laravel 5.5, the cleanest way to do this is:
Theme::with('user:userid,name,address')->get()
You add a colon and the fields you wish to select separated by a comma and without a space between them.
Using Model:
Model::where('column','value')->get(['column1','column2','column3',...]);
Using Query Builder:
DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);
If I good understood this what is returned is fine except you want to see only one column. If so this below should be much simpler:
return Response::eloquent(Theme::with('user')->get(['username']));
#You can get selected columns from two or three different tables
$users= DB::Table('profiles')->select('users.name','users.status','users.avatar','users.phone','profiles.user_id','profiles.full_name','profiles.email','profiles.experience','profiles.gender','profiles.profession','profiles.dob',)->join('users','profiles.user_id','=','users.id')
->paginate(10);
Check out, http://laravel.com/docs/database/eloquent#to-array
You should be able to define which columns you do not want displayed in your api.

Categories