doctrine: many to many relation with join table: how to add WHERE condition - doctrine

I have three tables:
Clients: (id, name, ...)
Files: (id, filename, type, data)
and join table:
Clients2Files (id, id_clients, id_files, created_at, deleted_at)
in php class Clients I want to get access to all client's files, but only to the files that hasn't been deleted (in sql speak WHERE deleted_at IS NULL)
Now I have code like this (in entity class Client), which selects all (even deleted) files:
/**
* #ManyToMany(targetEntity="File")
* #JoinTable(name="Clients2Files",
* joinColumns={#JoinColumn(name="id_clients", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="id_files", referencedColumnName="id")}
* )
*/
private $files;
How can I add condition WHERE deleted_at IS NULL to this doctrine code? To select only files that are not "deleted".

The annotations you added don't actually "SELECT" anything. All they do is tell Doctrine about your objects and their relations. What you want to do is:
$qb = $em->createQueryBuilder();
$qb->select('clients, files')
->from('Clients', 'clients')
->join('c.files', 'files')
->where('files.deleted_at IS NULL');
If you find yourself doing this often, and are using Doctrine 2.2+, you can take a look at filters: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html

Related

SQLSTATE[42S22]: (SQL: select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)

I'm trying to select all categories of a specific departement.
class Test extends Controller
{
public function test(){
$depts=Departement::find(1)->categories;
foreach ($depts as $dept){
echo $dept->name;
}
return view('test');
}
}
A quick google search tells me SQLSTATE[42S22] is the code for 'Column not found'.
When you call Departement::find(1)->categories, Eloquent makes 2 queries
Get THE Department whe primary key is equal to 1
Get ALL the Categories where their 'departement_id' attribute is equal to 1
Given the query in your error
select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)
It's clear there is no departement_id column in your categories table.
If there's no departement_id column in your categories table
Either:
Add it in a migration.
Add it directly in the db if you do not work with migrations
If you want to make another column act as the foreign key
update your relationship method to reflect that.
https://laravel.com/docs/5.8/eloquent-relationships

Laravel Getting Child table values with multiple Parent values

I need your help to find a solution in laravel 5. So let me explain my problem I have 4 tables lets suppose these are users, table1, table2, table3.
users and table1 have many to many relationship.
then table1 and table2 have many to many relationship.
and then table2 and table3 have many to many relationship.
Now on table3 controller i want to get all values with respect to a user. for example
$table1 = User::find(Auth::user()->id)->table1()->get()->lists('id');
$table2 = table1::whereIn('id',$table1)->table2()->get()->list('id');
$table3 = table2::whereIn('id',$table2)->table3()->get();
On table2 data i am getting the error of badmethodexception. I have googled and read the documentation but unable to get anywhere.
Can anyone help me how can i get the data please?
I have pivot table of table1_user, table1_table2 and table2_table3.
In user model i have function
public function table1(){
$this->blongstomany('App\table1');
}
In Table1 Model i have function
public function table2(){
$this->belongstomany('App\table2');
}
In Table2 Model i have function
public function table3(){
$this->belongstomany('App\table3');
}
I hope now it make sense.

Codeigniter : Want to Implement Left join by useing Doctrine 2 library

Please help me want to left join two table in Codeigniter with Orm docrtrine 2 libray.
Doctrine entity model doesn't give association for one to many and vice-versa. To allow these feature you have to update your entities with valid association. Below is an example for such two tables which contains user information in users table and there favorite meals in UserFavoriteMeals
For Left JOIN update needed in both entities for association explained below :
In user entity add onetomany association of UserFavoriteMeals where mappedby is the key on basis of which association happens in db.
/**
* #var \Entity\UserFavoriteMeals
*
* #OneToMany(targetEntity="Entity\UserFavoriteMeals", mappedBy="userid" )
* #JoinColumns({
* #JoinColumn(name="id", referencedColumnName="userId", nullable=true)
* })
*/
private $UserFavoriteMeals;
Simillary, Put manyToOne association in UserFavoriteMeals entity
/**
* #var \Entity\Users
*
* #ManyToOne(targetEntity="Entity\Users")
* #JoinColumns({
* #JoinColumn(name="userId", referencedColumnName="id", nullable=true)
* })
*/
private $userid;
In these manner we have to manage associations for Left JOIN, now simply write a Left JOIN query in below format :
$left_query = $this->em->createQuery("SELECT fm,u FROM Entity\userFavoriteMeals fm LEFT JOIN fm.userid u WHERE fm.userId = 231 ")->getArrayResult();
print_r($left_query);
$left_query_inverse = $this->em->createQuery("SELECT u,fm FROM Entity\Users u LEFT JOIN u.UserFavoriteMeals fm WHERE u.id = 4")->getArrayResult();
print_r($left_query_inverse);
First you need to integrate Doctrine into CodeIgnitor.
http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html
This is how you use custom query to left join two tables in Doctrine.
<?php
$query = $em->createQuery('SELECT u.id, a.id as article_id FROM CmsUser u LEFT JOIN u.articles a');
$results = $query->getResult(); // array of user ids and every article_id for each user
More on custom query :- http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html
If you want DQL way, which is preferred, it should be something like this.
$qb->select('u')
->from('Entity_User', 'u')
->leftJoin('u.profile','p')
->leftJoin('a.user_details','ud')
->where('u.id = :id')
->setParameter('id','100')
->getQuery();
More on DQL :- http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html
I hope this helps,
Cheers!

Magento - custom invoice number

I need to modify my default invoice number from 100000001 to 2012 - 00001.
I know where I can found increment_last_id in table eav_entity_store. But I don't know what I must set that to be taken new format of invoice number.
Please help with some advice.
If you want to do it manually then take a look # How to Change the Invoice Increment ID and Prefix in Magento (remember to always make a backup)
You can customize order/invoice/creditmemo/shipment number (increment_id) by editing the following class:
Mage_Eav_Model_Entity_Increment_Numeric
Especially, closely look at the code of the following methods:
getNextId(), getPrefix(), getPadLength(), format($id)
Now, you won't find the method definition for methods getPrefix(), getPadLength() because these are magic getter methods. You can define these methods according to your desire.
For an example:
public function getPrefix(){
$prefix = $this->_getData('prefix');
/* Do some customization */
return $prefix;
}
public function getPadLength()
{
$padLength = $this->_getData('pad_length');
/* Do some customization */
return $padLength;
}
This way, you don't have to manually change anything in the database structures for this to achieve.
Hope this will help you.
The best way to change invoice id is to run following simple sql query:
Check if invoice record exist in eav_entity_store table by running following query
select * from eav_entity_store where entity_type_id in (select entity_type_id from eav_entity_type where entity_type_code='invoice');
If no record exists, create one dummy invoice from magento backend. Then you will have one record in the table, now run following script:
update eav_entity_store set increment_last_id="YOUR_DESIRED_INVOICE_ID", increment_prefix='X-' where entity_type_id in (select entity_type_id from eav_entity_type where entity_type_code='invoice')
Try this out and create new invoice:
update eav_entity_store set increment_last_id="0001", increment_prefix='2002' where entity_type_id in (select entity_type_id from eav_entity_type where entity_type_code='invoice')
http://deepakbhatta.com/magento-set-custom-invoice-id/
This works fine to me.
Thanks

Using group by and order by in Doctrine

I have one database table called ms_message: with 6 columns (id, senderid, receiverid, content, isRead, receivedTime). I want to get the latest received message group by sender in Doctrine but I cannot run the sub query or use order by and group by as well.
The query in SQL looks like this:
SELECT * FROM (SELECT * FROM ms_message WHERE receiverId = :receiver ORDER BY receivedTime) GROUP BY senderId;
I don't think that Doctrine supports queries like SELECT * FROM (SELECT ...)

Resources