Doctrine where condition for many to one - doctrine

I have a many to one association mapping where many Exams have one subject
If I have to update marks property of all subject with exam id xxxx
I use
Update namespace/Exam e set e.marks = 4 where e.subject.id = xxxx
it is not working
can you please he
help me to do that in a proper way ?

You can not access e.subject.id without a join in your query. But a join is not possible in a Doctrine update statement, since its MySQL specific.
What should work is to compare the whole entity:
$subject = $this->getEntityManager()->getRepository('namespace\subject')
->find(xxx);
$query = $this->getEntityManager()->createQueryBuilder()
->update('namespace\Exam', 'e')
->set('e.marks', '4')
->where('e.subject = :subject')
->setParameter('subject', $subject);
Or, if you don't want to have another database query and the primary key of your subject entity consists only of one column (e.g. id), you could also compare with this primary key:
$query = $this->getEntityManager()->createQueryBuilder()
->update('namespace\Exam', 'e')
->set('e.marks', '4')
->where('e.subject = :id')
->setParameter('id', xxx);
Also have a look at this question, the user wasn't able to join in his update statement too.
Edit: added more general approach

Related

Laravel - How to paginate united Many To Many(Polymorphic) collection?

Trying to figure out how to fetch two related models(obviously united) of my Many To Many(Polymorphic) relationship.
What we have:
3 models: Bucket, Template and DesignPack.
Bucket has Many-To-Many(Polymorphic) relationship with Template and DesignPack(It means we have pivot table bucketables).In essence Bucket can have(be related with) both: Template and DesignPack.
Laravel 6.*
What I want to get:
I want to get a Bucket templates and design packs united in one collection and paginated!
Please check one of the solutions I've tried:
$templates = Bucket::find($bucket_id)->templates()->select(['id', 'file_name as name', 'size', 'preview']);
$design_packs = Bucket::find($bucket_id)->dps()->select(['id', 'name', 'size', 'preview']);
$all = $templates ->union($design_packs )->paginate(10);
Unfortunately that solution throws me the error(thought I checked what each request returns and it returns the same fields, not different):
"SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select `id`, `size`, `preview`, `bucketables`.`bucket_id` as `pivot_bucket_id`, `bucketables`.`bucketable_id` as `pivot_bucketable_id`, `bucketables`.`bucketable_type` as `pivot_bucketable_type` from `design_packs` inner join `bucketables` on `design_packs`.`id` = `bucketables`.`bucketable_id` where `bucketables`.`bucket_id` = 3 and `bucketables`.`bucketable_type` = App\DesignPack and `design_packs`.`deleted_at` is null) union (select `id`, `size`, `preview` from `templates` inner join `bucketables` on `templates`.`id` = `bucketables`.`bucketable_id` where `bucketables`.`bucket_id` = 3 and `bucketables`.`bucketable_type` = App\Template and `templates`.`deleted_at` is null))"
Are there any different way to get what I want?
May be examples, documentation links or any helpful ideas?
Will be so grateful guys for any help!
Thank you!
You can pass closure to queries:
$templates = Bucket::whereHas('templates', function($query) use $bucket_id {
$query->where('bucket_id', $bucket_id);
})->get();
$designPacks = Bucket::whereHas('dps', function($query) use $bucket_id {
$query->where('bucket_id', $bucket_id);
})->get();
then merge 2 eloquent collections:
$mergedCollections = $templates->merge($designPacks);
now you have a collection of both results, you can select specific fields, limit the results or etc. you may want take a look at Laravel collection helpers.
also if you insist to use the union, you may want to take a look at this treat:
The used SELECT statements have a different number of columns (REDUX!!)

Laravel inject SQL Query into Model Collection

I have a Laravel Controller method with the following code:
$listings = LikedListing::where('user_id', '=', $user->id)
->with('Listing.Photos')
->get();
This should return a collection of LikedListing records with Photos attached to each likedlisting record.
I have this SQL Query I need to inject into each record as well:
select u.id, l.address, u.first_name, u.last_name, ll.score
from listings l
left join liked_listings ll on ll.listing_id = l.id
left join users u on u.id = ll.user_id
where u.id in (
select secondary_user
from user_relationships
where primary_user = $primaryUser
)
and ll.listing_id = $listingId
Where $primaryUser = $user->id And $listingId is equal to the listingid inside each record in the collection.
I have absolutely no idea how to do this.
Maybe theres a model way of performing this? UserRelationship model has a primary_user column, which connects to a $user->id, and there is a secondary_user column, which acts like a follower userid, which is what we need in the final result (a list of all related users per listing)`
Can someone who has much far superior knowledge with Laravel please assist
My goal is to have the current collection of listing records with associated photos as well as following users (secondary_user) from the user_relationship table related to the primary_user (the logged in user) who have a record using user_id with the secondary_user value for that listing in the likedlisting table (obv assoicated with the listing_id). I already provided a raw sql query if thats the only option.
So in simple terms all related users who have liked a listing that the primary user has liked as well should be added to each listing record

Joining multiple tables on an already joined table using Eloquent

I have the following which brings back all users in a group along with their posts.
$group = Group::where('id', $id)->with('users.posts')->firstOrFail();
However, what I need is an additional join on the users to bring back additional (hasMany) information.
What I want is something like this (although this doesn't work)
$group = Group::where('id', $id)->with('users.posts,houses')->firstOrFail();
The sql would look something like
SELECT * FROM groups
JOIN group_users ON groups.id = group_users.group_id
JOIN users ON users.id = group_users.user_id
JOIN posts ON posts.user_id = users.id
JOIN house_users ON house_users.user_id = users.id
JOIN houses ON houses.id = house_users.house_id
WHERE groups.id = 123
If you pass a single argument to with(), it will look for a relationship with a matching name. Using a single string with a comma won't work as it won't parse and respect it. Since you're trying to use multiple relationships, this needs to be multiple signature, which there are a couple ways to accomplish.
First, array syntax:
->with(["users.posts", "houses"])
Second, multiple arguments:
->with("users.posts", "houses")
Either method will specify that you want multiple relationships loaded to your initial query; preference is given to whichever you find easier to read.

codeigniter active record join 2 databases

Can I use a $this->db->join('database.table') without inserting the second parameter of this function? I need to connect 2 databases, but they dont have nothing that binds them. I know that it works with SQL because I have tried it, however I want to change the model using active record, because I find it more flexible etc.. but I dont know how to insert the join
$this->db->select('users.user_id');
$this->db->distinct();
$this->db->from('users');
$this->db->join('user_detail', 'users.user_id = user_detail.id', 'left');
and now something like:
$this->db->join('cities.city');
So the SQL should be like:
SELECT DISTINCT users.user_id FROM users LEFT JOIN .... JOIN cities.city
Instead of:
SELECT DISTINCT users.user_id FROM users LEFT JOIN .... JOIN cities.city ON
What I actually have.
Please help. Thank you.
You cannot. If you look at the CI core files, you will see that ON will always be passed. I didn't realize this was the case until I checked the system files.
$join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;
Reference in /system/database/DB_active_rec.php line 340. Even in the latest version (GitHub) this is still the case, although either ON or USING() will be used.
Your best bet is to just use $this->db->query():
$this->db->query('SELECT DISTINCT users.user_id FROM users LEFT JOIN .... JOIN cities.city');
Update: Since you are using 2.1.3, you can hack the core files (since I do not believe there is a way to extend CI active records). Although you shouldn't edit core files on a normal basis, at least this will give you what you need. Open /system/database/DB_active_rec.php:
Change line 310 to:
public function join($table, $cond, $type = '', $use_on = TRUE)
Change line 340 to (which now becomes 2 lines):
$on_cond = ($use_on === TRUE) ? ' ON '.$cond : NULL;
$join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).$on_cond;
Now in your model when you call your join() pass a 4th parameter, FALSE, to turn off the ON:
$this->db->join('cities.city', NULL, '', FALSE);

Can I force the auto-generated Linq-to-SQL classes to use an OUTER JOIN?

Let's say I have an Order table which has a FirstSalesPersonId field and a SecondSalesPersonId field. Both of these are foreign keys that reference the SalesPerson table. For any given order, either one or two salespersons may be credited with the order. In other words, FirstSalesPersonId can never be NULL, but SecondSalesPersonId can be NULL.
When I drop my Order and SalesPerson tables onto the "Linq to SQL Classes" design surface, the class builder spots the two FK relationships from the Order table to the SalesPerson table, and so the generated Order class has a SalesPerson field and a SalesPerson1 field (which I can rename to SalesPerson1 and SalesPerson2 to avoid confusion).
Because I always want to have the salesperson data available whenever I process an order, I am using DataLoadOptions.LoadWith to specify that the two salesperson fields are populated when the order instance is populated, as follows:
dataLoadOptions.LoadWith<Order>(o => o.SalesPerson1);
dataLoadOptions.LoadWith<Order>(o => o.SalesPerson2);
The problem I'm having is that Linq to SQL is using something like the following SQL to load an order:
SELECT ...
FROM Order O
INNER JOIN SalesPerson SP1 ON SP1.salesPersonId = O.firstSalesPersonId
INNER JOIN SalesPerson SP2 ON SP2.salesPersonId = O.secondSalesPersonId
This would make sense if there were always two salesperson records, but because there is sometimes no second salesperson (secondSalesPersonId is NULL), the INNER JOIN causes the query to return no records in that case.
What I effectively want here is to change the second INNER JOIN into a LEFT OUTER JOIN. Is there a way to do that through the UI for the class generator? If not, how else can I achieve this?
(Note that because I'm using the generated classes almost exclusively, I'd rather not have something tacked on the side for this one case if I can avoid it).
Edit: per my comment reply, the SecondSalesPersonId field is nullable (in the DB, and in the generated classes).
The default behaviour actually is a LEFT JOIN, assuming you've set up the model correctly.
Here's a slightly anonymized example that I just tested on one of my own databases:
class Program
{
static void Main(string[] args)
{
using (TestDataContext context = new TestDataContext())
{
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Place>(p => p.Address);
context.LoadOptions = dlo;
var places = context.Places.Where(p => p.ID >= 100 && p.ID <= 200);
foreach (var place in places)
{
Console.WriteLine(p.ID, p.AddressID);
}
}
}
}
This is just a simple test that prints out a list of places and their address IDs. Here is the query text that appears in the profiler:
SELECT [t0].[ID], [t0].[Name], [t0].[AddressID], ...
FROM [dbo].[Places] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[AddressID],
[t1].[StreetLine1], [t1].[StreetLine2],
[t1].[City], [t1].[Region], [t1].[Country], [t1].[PostalCode]
FROM [dbo].[Addresses] AS [t1]
) AS [t2] ON [t2].[AddressID] = [t0].[AddressID]
WHERE ([t0].[PlaceID] >= #p0) AND ([t0].[PlaceID] <= #p1)
This isn't exactly a very pretty query (your guess is as good as mine as to what that 1 as [test] is all about), but it's definitively a LEFT JOIN and doesn't exhibit the problem you seem to be having. And this is just using the generated classes, I haven't made any changes.
Note that I also tested this on a dual relationship (i.e. a single Place having two Address references, one nullable, one not), and I get the exact same results. The first (non-nullable) gets turned into an INNER JOIN, and the second gets turned into a LEFT JOIN.
It has to be something in your model, like changing the nullability of the second reference. I know you say it's configured as nullable, but maybe you need to double-check? If it's definitely nullable then I suggest you post your full schema and DBML so somebody can try to reproduce the behaviour that you're seeing.
If you make the secondSalesPersonId field in the database table nullable, LINQ-to-SQL should properly construct the Association object so that the resulting SQL statement will do the LEFT OUTER JOIN.
UPDATE:
Since the field is nullable, your problem may be in explicitly declaring dataLoadOptions.LoadWith<>(). I'm running a similar situation in my current project where I have an Order, but the order goes through multiple stages. Each stage corresponds to a separate table with data related to that stage. I simply retrieve the Order, and the appropriate data follows along, if it exists. I don't use the dataLoadOptions at all, and it does what I need it to do. For example, if the Order has a purchase order record, but no invoice record, Order.PurchaseOrder will contain the purchase order data and Order.Invoice will be null. My query looks something like this:
DC.Orders.Where(a => a.Order_ID == id).SingleOrDefault();
I try not to micromanage LINQ-to-SQL...it does 95% of what I need straight out of the box.
UPDATE 2:
I found this post that discusses the use of DefaultIfEmpty() in order to populated child entities with null if they don't exist. I tried it out with LINQPad on my database and converted that example to lambda syntax (since that's what I use):
ParentTable.GroupJoin
(
ChildTable,
p => p.ParentTable_ID,
c => c.ChildTable_ID,
(p, aggregate) => new { p = p, aggregate = aggregate }
)
.SelectMany (a => a.aggregate.DefaultIfEmpty (),
(a, c) => new
{
ParentTableEntity = a.p,
ChildTableEntity = c
}
)
From what I can figure out from this statement, the GroupJoin expression relates the parent and child tables, while the SelectMany expression aggregates the related child records. The key appears to be the use of the DefaultIfEmpty, which forces the inclusion of the parent entity record even if there are no related child records. (Thanks for compelling me to dig into this further...I think I may have found some useful stuff to help with a pretty huge report I've got on my pipeline...)
UPDATE 3:
If the goal is to keep it simple, then it looks like you're going to have to reference those salesperson fields directly in your Select() expression. The reason you're having to use LoadWith<>() in the first place is because the tables are not being referenced anywhere in your query statement, so the LINQ engine won't automatically pull that information in.
As an example, given this structure:
MailingList ListCompany
=========== ===========
List_ID (PK) ListCompany_ID (PK)
ListCompany_ID (FK) FullName (string)
I want to get the name of the company associated with a particular mailing list:
MailingLists.Where(a => a.List_ID == 2).Select(a => a.ListCompany.FullName)
If that association has NOT been made, meaning that the ListCompany_ID field in the MailingList table for that record is equal to null, this is the resulting SQL generated by the LINQ engine:
SELECT [t1].[FullName]
FROM [MailingLists] AS [t0]
LEFT OUTER JOIN [ListCompanies] AS [t1] ON [t1].[ListCompany_ID] = [t0].[ListCompany_ID]
WHERE [t0].[List_ID] = #p0

Resources