EF Core - Include multiple child tables [duplicate] - linq-to-sql

This question already has answers here:
Include several references on the second level
(2 answers)
Closed 2 years ago.
Im trying to load multiple related child tables (table B and B1, B2), but ThenInclude works only for one child table. Im using EF Core 3.1, any idea how to do it?
This way works for one child table:
var result = context.A
.Include(x => x.B)
.ThenInclude(x => x.B1);
But I want to load related not only from table B1, but from B2 too.
enter image description here

You have to repeat Include again
var result = context.A
.Include(x => x.B)
.ThenInclude(x => x.B1)
.Include(x => x.B)
.ThenInclude(x => x.B2);

Related

Laravel Eloquent create method skipping IDs and returning them

I'm simply trying to create a new model through Eloquent's create method. However, we're seeing that the new model will sometimes contain an id that has been skipped in mysql. This id is designated as an autoincrement column in mysql.
We are also seeing this happen when using DB:getPdo()->lastInsertId() immediately after the model has been created.
$questionResponse = $response->questionResponses()->create([
'survey_question_id' => $question->id,
'response' => 5
]);
$response_id = $questionResponse->id; // weve also used DB::getPdo()->lastInsertId();
Queue::push('TheWorker', array('survey_id' => $survey->id, 'response_id' => $response_id, 'question_id' => $question->id, 'user_id' => $user->id, 'student_target_id' => $student_target_id));
TheWorker then fails due to receiving an incorrect $repsonse_id that doesn't exist in the DB.
We would expect that the newly created model would contain the id that matches the record created in mysql.
Thanks in advance!

Multiple Fields with a GroupBy Statement in Laravel

Already received a great answer at this post
Laravel Query using GroupBy with distinct traits
But how can I modify it to include more than just one field. The example uses pluck which can only grab one field.
I have tried to do something like this to add multiple fields to the view as such...
$hats = $hatData->groupBy('style')
->map(function ($item){
return ['colors' => $item->color, 'price' => $item->price,'itemNumber'=>$item->itemNumber];
});
In my initial query for "hatData" I can see the fields are all there but yet I get an error saying that 'colors', (etc.) is not available on this collection instance. I can see the collection looks different than what is obtained from pluck, so it looks like when I need more fields and cant use pluck I have to format the map differently but cant see how. Can anyone explain how I can request multiple fields as well as output them on the view rather than just one field as in the original question? Thanks!
When you use groupBy() of Laravel Illuminate\Support\Collection it gives you a deeper nested arrays/objects, so that you need to do more than one map on the result in order to unveil the real models (or arrays).
I will demo this with an example of a nested collection:
$collect = collect([
collect([
'name' => 'abc',
'age' => 1
]),collect([
'name' => 'cde',
'age' => 5
]),collect([
'name' => 'abcde',
'age' => 2
]),collect([
'name' => 'cde',
'age' => 7
]),
]);
$group = $collect->groupBy('name')->values();
$result = $group->map(function($items, $key){
// here we have uncovered the first level of the group
// $key is the group names which is the key to each group
return $items->map(function ($item){
//This second level opens EACH group (or array) in my case:
return $item['age'];
});
});
The summary is that, you need another loop map(), each() over the main grouped collection.

Query to find where associated model (has many) is empty in cakephp

I have a model named Application. And Application is associated to has_many model named Location.
Application has many Location
In my Application query:
$this->Application->find('all', array('conditions' => 'Application.status' => 'accepted'));
I'm finding applications where status is accepted.
Next thing that I would like to achieve is to find Application records where associated Location is empty/null or in other words where count of Location records is 0.
I tried to make join query like this:
$join_query = array(
'table' => 'locations',
'alias' => 'Location',
'type' => 'INNER',
'conditions' => array(
'Location.application_id = Application.id',
'OR' => array(
array('Location.id' => NULL)
)
)
);
But seems like it's just querying Application records that do have associated Location records.
Thanks in advanced if you guys have any idea(s).
You need to use a left join, not an inner join. Inner join will get only those results that have a row in both of the tables you are joining, where you want only results where there is only a row in the left table. Left joins will get all the results in the left table, regardless if there's a row associated with it in the right table. Then add a condition after the join is complete, to only select those joined results where Location.id is null.
$this->Application->find('all',
array(
'conditions' => array('Location.id' => null),
'joins' => array(
array(
'table' => 'locations',
'alias' => 'Location',
'type' => 'LEFT',
'conditions' => array('Location.application_id = Application.id')
),
),
)
);
Your query says "find any application and its location with application_id = id, AND (1 OR where location.id = null)", so that will match any application that has location.
What I'd do is to leave joins and just use containable and counts. With plain sql I'd use a left join and count the Locations, like in this example. But cake doesn't behave well with not named columns, like "COUNT(*) AS num_locations", so I tend to avoid that.
I'd transform your query to a containtable one
$apps = this->Application->find('all', array('contains'=>'Location'));
foreach($apps as $app) {
if (count($app['Location']) <= 0)
//delete record
}
You could also implement a counterCache, and keep in a BD column the number of locations per application, so the query can be a simple find like
$this->Application->find('all', array('conditions'=>array('location_count'=>0)));
Ooooor, you could add a virtual field with "SUM(*) as num_locations" and then use your join with "left outter join" and compare "num_locations = 0" on the conditions.
Those are the options that comes to mind. Personally I'd use the first one if the query will be a one time/not very used one. Probably put it in the Application model like
public function findAppsWithNoLocations() {
$apps = this->Application->find('all', array('contains'=>'Location'));
foreach($apps as $app) {
if (count($app['Location']) <= 0)
//delete record
}
}
But the other two options would be better if the sum of locations per app is going to be a recurrent query you'll search for.
EDIT
And of course Kai's answer options that does what you want xD. This tendency to complicate things will be the end of me... Well, will leave the answer here to show a reference to other convoluted options (specifically counterCache if you'll need to count the relations a lot of times).
i know this is already some time ago.
i could manage it this way:
public function getEmpty($assoc) {
foreach($this->find('all') as $c){
if(empty($c[$assoc])) $return[] = $c;
}
return $return;
}
now i got all entries that have an empty associated data.
in my controller i call the function like this:
$ce = $this->Company->getEmpty('CompaniesUsers');
companies Users is the Empty Associated model i want to check.

Join DB tables with hasMany association - store in array

In a cakePHP application I am building, a profile can have multiple locations; the tables are called "profiles" and "locations" and in the model classes I have defined a HasMany relationship. Now I want the user to be able to search profiles based on their locations. After reading some questions here and the CakePHP Cookbook, I have decided I need to use SQL joins (in reality more tables are involved, and the result of a search should be based on conditions concerning different tables).
I have written the following function inside my Profile model:
public function findProfiles($long, $lat){
$options['joins'] = array(
array('table' => 'locations',
'alias' => 'Location',
'type' => 'Inner',
'conditions' => array('Location.profile_id = Profile.id'))
);
$options['order'] = array('Location.lng ASC'); //this is just as trial
return $this->find('all',$options);
}
The code works, but I get a copy of a profile for each location it possesses. That is, if a profile possesses 5 positions, I get five instances of that profile (each instance containing all five positions!)
How can I achieve this?
[edit]
eg. let's assume I only have one profile, with two positions. I get:
result[0][Profile]
[Position][0]
[1]
[1][Profile]
[Position][0]
[1]
Where the data in result[0] and result[1] is identical.
The problem happens because of the type of join used. With inner join you'll get this return with your query
profile_id location_id
---------------------------
1 2
1 3
And cake understands that as two records of Profile, so you get repeated Profiles with the same info.
If this were all the extent of your problem, I'd say "go with Containable behaviour and forget joins", but since you said there are more tables involved, maybe the type of join can't be changed. So to get the unique Profile without repetitions, you'll have to GROUP BY the query to get
profile_id location_id
---------------------------
1 2 & 3
with a code similar to this
$options['joins'] = array(
array('table' => 'locations',
'alias' => 'Location',
'type' => 'Inner',
'conditions' => array('Location.profile_id = Profile.id')),
'group' => 'Profile.id'
);
and you'll get rid of repetitions. For future problems like this, is best to first check the actual query that gets send to the DB, check yourself if the result that the DB gives you is what you want, and if not, see what you can do in cake to change it.

UPDATED: Magento add customer attribute filter to order grid

I have extended the Mage_Adminhtml_Block_Sales_Order_Grid class with a custom module to add several customer attributes (Magento EE 1.10) to the grid.
Two of the attributes I added are text fields (i.e. they live in the customer_entity_varchar table, and I was able to add them to the collection and display them in the grid. So far so good.
A third attribute is a select, so the values live in the customer_entity_int, the eav_attribute_option and the eav_attribute_option_value tables. I added the necessary values to the collection (using $collection->getSelect()->joinLeft(.....). Again, so far so good.
My problem is being able to display and filter the attribute at the same time.
Inside the _prepareColumns() function in my MyCompany_MyModule_Block_Adminhtml_Order_Grid class, if I add a column like this, - as expected - I can display the values of the attribute on each row, but I don't get a drop down filter in the header:
protected function _prepareColumns()
{
...
$this->addColumn('bureau', array(
'header' => Mage::helper('sales')->__('Bureau'),
'index' => 'bureau',
'type' => 'text'
));
...
}
Following the example of status, and adding the column like this, gives me the drop down filter in the header, but it no longer displays the values for the attribute in each row:
protected function _prepareColumns()
{
...
$this->addColumn('bureau', array(
'header' => Mage::helper('sales')->__('Bureau'),
'index' => 'bureau',
'type' => 'options',
'options' => $this->_getBureauOptions(),
'filter_index' => 'value_option_table.option_id'
));
...
}
protected function _getBureauOptions()
{
$bureau = Mage::getResourceModel('eav/entity_attribute_collection')
->setCodeFilter('bureau')
->getFirstItem();
$bureauOptions = $bureau->getSource()->getAllOptions(false);
$optionsArr = array();
foreach ($bureauOptions as $option) {
$optionsArr[$option['value']] = $option['label'];
}
return $optionsArr;
}
Any advice / explanation would be much appreciated.
UPDATE:
It turns out that my code also causes a SQL error in a multi-website environment when an admin user only has permissions for some websites:
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'store_id' in where clause is ambiguous"
#clockworkgeek had the answer to the first part of my question.
The problem was that my joinLeft() was retrieving text values from the attribute options, while I should have been retrieving integer values when using 'type => 'options'.
Once I changed my joinLeft() to only retrieve integer values from customer_entity_int (actually a simpler join), the filtering and display worked flawlessly - thank you sir.
I will re-post my second issue (about SQL errors caused by permissions) as a separate question.