Laravel and Eloquent: Specifying columns in when retrieving related items - select

This is a followup post to: Laravel 4 and Eloquent: retrieving all records and all related records
The solution given works great:
$artists = Artist::with('instruments')->get();
return \View::make('artists')->withArtists($artists);
It also works with just:
$artists = Artist::get();
Now I'm trying to specify the exact columns to return for both tables. I've tried using select() in both the statement above and in my Class, like this:
ArtistController.php
$artists = Artist::select('firstname', 'lastname', 'instruments.name')->get();
or:
$artists = Artist::with(array('instruments' => function($query) {
$query->select('name');
}))->get();
(as suggested here and while this doesn't throw an error, it also doesn't limit the columns to only those specified)
or in Artist.php:
return $this->belongsToMany('App\Models\Instrument')->select(['name']);
How would I go about getting just the firstname and lastname column from the artists table and the name column from instruments table?

Not sure what I was thinking. I think working on this so long got me cross-eyed.
Anyhow, I looked into this a lot more and searched for answers and finally posted an issue on GitHub.
The bottom line is this is not possible as of Laravel v4.1.
https://github.com/laravel/laravel/issues/2679
This solved it:
Artists.php
public function instruments() {
return $this->hasMany('App\Models\Instrument', 'id');
}
Note that I changed this to a hasMany from a belongsToMany which makes more sense to me as a musicians (or Artist) would have many Instruments they play and an Instrument could belong to many Artists (which I also alluded to in my previous questions referenced above). I also had to specify 'id' column in my model which tells the ORM that instrument.id matches artist_instrument.id. That part confuses me a bit because I thought the order for hasMany was foreign_key, primary_key, but maybe I'm thinking about it backwards. If someone can explain that a bit more I'd appreciate it.
Anyhow, the second part of the solution...
In ArtistsController.php, I did this:
$artists = Artist::with(array(
'instruments' => function($q) {
$q->select('instruments.id', 'name');
})
)->get(array('id', 'firstname', 'lastname'));
That gives me exactly what I want which is a collection of Artists that contains only the firstname and lastname columns from the artists table and the name column for each of the instruments they play from the instruments.

$artists = Artist::with(array('instruments' => function ($query) {
$query->select('id', 'name');
}))->get('id', 'firstname', 'lastname');

Related

Extbase "findBy" with multiple parameters

I got an extension in which i want to include some filters, i know figured out that i can filter the results that are shown of my listAction() by using findBy.
I tested it and it worked like this:
$cars = $this->carRepository->findByCarid("1");
$this->view->assign('cars', $cars);
My problem now is i need to filter the result with more than one Parameter, what if i want to add findByColor("blue") so it gives me all cars wit hid 1 and color blue? What solution does extbase have for that kind of search queries? i can`t find anything good or understandable in the documentation.
You have to extend you repository and code this functionality on your own. Extbase offers you a simple but powerful API to do so.
class whatEverYourRepositoryIsCalled extends \TYPO3\CMS\Extbase\Persistence\Repository {
public function findByFilter($carId, $color) {
// Create empty query = select * from table
$query = $this->createQuery();
// Add query options
return $query->matching(
// ALL conditions have to be met (AND)
$query->logicalAnd(
// table column carId must be euqal to $carId
$query->equals('carId', $carId),
// table column color must be euqal to $color
$query->equals('color', $color)
)
);
}
}
This is a quite simple approach to your problem. In a real world scenario I would probably use an array of filter criteria to do the filtering like array('carId' => 1, 'color' => 'blue'). Inside of findByFilter() those values would be extracted and added to the query.
The key is to build the desired query. A quite comprehensive explanation of how to do that can be found at http://blog.typoplanet.de/2010/01/27/the-repository-and-query-object-of-extbase/. Unfortunately it's not completely up to date but the part about constructing queries is still valid.

Select custom columns from Laravel belongsToMany relation

Im trying to select only specific attributes on the many-to-many relation users, just like in one-to-one. But using select() on belongsToMany() seem to be ignored and i'm still getting all the User attributes.
class Computer extends Eloquent {
public function users() {
return $this->belongsToMany("User")->select("email");
}
public function admin() {
return $this->hasOne("User")->select("email");
}
}
Computer::with("users")->get();
Is there a way of filtering only specified columns from related entity with belongsToMany()?
Yes, you actually can.
Computer::with("users")->get(array('column_name1','column_name2',...));
Be careful though if you have the same column name for both tables linked by your pivot table. In this case, you need to specify the table name in dot notation, tableName.columnName. For example if both users and computer has a column name id, you need to do :
Computer::with("users")->get(array('users.id','column_name2',...));
According to Taylor Otwell it is not currently possible: https://github.com/laravel/laravel/issues/2679
I have tried to use a lists('user.email') at the end of the query but I can't make it work.
Computer::with(["users" => function($query){
$query->select('column1','column2','...');
}])->get();

Trace Entity Framework 4.0 : Extra queries for foreign keys

In the following example, we insert an entity called taskinstance to our context. we have a foreign key FK_Contract that we set at 2.
entity.FK_Contract = 2;
context.TaskInstances.AddObject(entity);
The query generated by entity framework is a simple insert. (everything is fine)
However, the following query works differently.
int contractId = context.Contracts.Where((T) => T.Name == contractName).Single().Id;
entity.FK_Contract = contractId;
context.TaskInstances.AddObject(entity);
In the trace created by entity framework we see without surprise the query selecting the Id according a contractName but we also see an extra request looking like:
select id,... from [TaskInstances] WHERE [Extent1].[FK_Task] = #contractId
This extra query leads to many problems, especially when we work with a foreign table with millions of record. The network goes down!
Therefore we 'd like to figure out the purpose of this extra query and the way to make it disappear.
It looks like the extra query is populating a collection of tasks on the returned Contract object. Try projecting just the column you want:
int contractId = context.Contracts
.Where(T => T.Name == contractName)
.Select(T => T.Id)
.Single();

entity framework 4.0 multiple joins

This is my real world example.
I have 4 tables:
Person
Plan
Coverage
CoveredMembers
Each person can have many plans, each of those plans can have many coverages. Each of those coverages can have many CoveredMembers.
I need a query that will apply a filter on Plan.PlanType == 1 and CoveredMembers.TermDate == null.
This query should bring back any person who has a medical type plan that is not terminated.
This SQL statement would do just that:
SELECT Person.*, Plans.*, Coverages.*, CoveredMembers.*
FROM Person P
INNER JOIN Plan PL ON P.PersonID = PL.PersonID
INNER JOIN Coverage C on PL.PlanID = C.PlanID
INNER JOIN CoveredMember CM on C.CoverageID = CM.CoverageID
WHERE CM.TermDate = NULL AND PL.PlanType = 1
I have figured out how to do this using anonymous types, but I sometimes need to update the data and save back to the database - and anonymous types are read only.
I was given a solution that did work using JOIN but it only brought back the persons (albeit filtered the way I needed). I can then loop through each person:
foreach (var person in persons) {
foreach (var plan in person.Plans{
//do stuff
}
}
But wouldn't that make a db call for each iteration of the loop? I have 500 persons with 3 unterminated medical plans each, so it would call the db 1500 times?
This is why I want to bring the whole data tree from Persons to CoveredMembers back in one shot. Is this not possible?
I believe this is accomplished in two parts:
Your query to determine the people you wish to have returned based on your criteria as discussed in this question previously: Entity framework. Need help filtering results
Properly setting the navigation properties for entities you want brought together to be eagerly loaded: http://msdn.microsoft.com/en-us/data/jj574232.aspx
For example if your Person entity looks like:
public class Person {
public List<Plan> Plans {get; set;}
...
}
When returning data from the dbcontext you can also use explicit eager loading with the include option:
var people = context.People
.Include(p => p.Plans)
.ToList();
....
If these are nested - coverage is part of plan, etc (which it looks like, it goes something like):
var people = context.People
.Include(p => p.Plans.Select(pl=>pl.Coverage).Select(c=>c.CoveredMembers)))
.ToList();
....
I am making some assumptions about your data model here, and my code above probably needs a little tweaking.
EDIT:
I might need someone else to weigh in here, but I don't think you can add the where clause into an include like that (my example above leads you that way a bit by putting the include on the context object, instead return an IQueryable with your conditions set as solved in your first post (without a ToList() called on it) and then use the code you wrote above without the Where clauses:
From first post (you supplied different criteria in this one, but same concept)
var q = from q1 in dbContext.Parent
join q2 in dbContext.Children
on q1.key equals q2.fkey
join q3 in ........
where q4.col1 == 3000
select q1;
Then:
List<Person> people = q.Include(p => p.Plans
.Select(pl => pl.Coverages)
.Select(c => c.CoveredMembers).ToList();
Again, doing this without being able to troubleshoot - I am sure it would take me a few attempts to iron this one out too.

Using relationships to search in DBIx::Class

I am starting learning DBIx::Class and I have a doubt in searching in a related table:
Consider the following code:
my $books = $author->search_related('books', { name => 'Titanic' });
my $books = $author->books->search({name => 'Titanic'});
What I want is to only searches for books named 'Titanic' by the author in $author.
This two searches return the same resultset?
If yes, what is the best way and why?
If no, what is the difference?
search_related is a Resultset method. You'd use that if you had a resultset of Authors and you wanted to get a resultset of all of their books named 'Titanic'.
my $books = $schema->resultset('Author')->search({ last_name => 'Smith' })
->search_related('books', { name => 'Titanic' });
If $author is a row object, representing one row, then your second line is how you'd search his books.
my $books = $author->books->search({ name => 'Titanic' });
The distinction between rows and resultsets is one of the core concepts of DBIx::Class. You might want to review the DBIC Manual Intro. #dbix-class on irc.perl.org is usually pretty active so you can find help there as well.