query including many tables cakephp 3 - cakephp-3.0

Using cakephp 3 I want to have the same result that I will have if I execute the query below (Get all paiements of appartements that belongs to Complex XX) :
SELECT p.*
FROM immeubles i inner join appartements a on i.id=a.immeuble_id
inner join paiements p on p.appartement_id = a.id
where i.complex_id=4
tables used are :
Immeubles (id,name,complex_id(Foreign Key));
Appartements(id, num,immeuble_id(foreign key))
paiements(id,montant,appartement_id(foreign key))
I tried first to extract all appartements that belongs to complex=4 by using the code below but i don't know how to concatenate the results with the table Paiements in order to show all fields of paiements :
$this->Appartements->find()
->join([
'i' => [
'table' => 'Immeubles',
'type' => 'inner',
'conditions' => [
'i.id=Appartements.immeuble_id',
'i.complex_id' => 4
]]]);

Related

I do not understand joining tables

I'm using Cake version 2.5.4
I have two tables.
A call arbols which consists of the following fields:
id (int 11)
nombre (varchar (255)
especie:id (int 11)
The second table called fotos consists of the following fields:
id (int 11)
foto (varchar 255)
foto_dir (varchar 255)
arbol_id (int 11)
Although the Arbol model is related to the Especie model,
I leave it aside to the latter because it is not a reason for consultation.
The Arbol Model has a hasMany relationship with the Foto model.
In the Arbol model I have the following:
public $hasMany = array(
'Foto'=> array(
'className' => 'Foto',
'foreignKey' => 'arbol_id',
'dependent' => true
)
);
In the Foto model I have the following:
public $belongsTo = array(
'Arbol'=> array(
'className'=>'Arbol',
'foreign_key'=>'arbol_id'
)
);
Now, inside ArbolsController in public function view ($ id = null)
I want to do the following SQL query:
SELECT * FROM arboles as a join fotos as f on a.id=f.arbol_id
So I return all the photos related to an id of a particular tree passed as parameter in view
If this query is done using MySQL
$registros=mysqli_query($conexion," select * from arboles as a join fotos as f on a.id=f.arbol_id")
it works.
But if I want to do it using the query method in such ways:
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
It does not work
Reading the Cookbook I see there is a way to make joins.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
I dont understand her
I would appreciate it if you can explain it to me.
From already thank you very much!
You shouldn't be using the query method directly if you can avoid it.
What you can do is using a standard find, joining your tables with containable (or linkable).
Something like this should work:
$registros = $this->Arbol->find('all', array(
'contain' => 'Foto'
));
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
There is another way by you can join the tables in cakephp i.e customized joins
Create an array of tables whom you want to join, such as
$joins = array(
array(
'table' => 'fotos',//Table name
'alias' => 'Foto', //Model name
'type' => 'INNER', // type of join
'conditions' => array(
'Arbol.id = Foto.arbol_id'
) //Condition for join
)
);
$this->Arbol->find('all', array(
'joins' => $joins,
'conditions'=> array(Arbol.id => $id),
'fields' => array()
))
This will return all the photos information related to an id

CakePHP 3.x - SUM() on ManyToMany

I am getting stuck on using SQL functions queries made in CakePHP 3 in combinations with associations.
The situation is as follows: I have three tables, a 'products' table, an 'orders' table and a join table called 'orders_products'.
In the index of OrdersController I would like to add the total price (= sum of relevant product prices) to the table of orders. In SQL this exactly can be done with the following query:
SELECT orders.id, SUM(products.price)
FROM orders
LEFT JOIN orders_products
ON orders.id = orders_products.order_id
LEFT JOIN products
ON orders_products.product_id = products.id
GROUP BY orders.id;
I figured to following controller code should do the trick:
$orders = $this->Orders->find('all')->contain(['Products']);
$orders
->select(['total_price' => $orders->func()->sum('Products.price')])
->group('Orders.id');
However, when the query object is executed, I get an error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'Products.price' in 'field list'
...Even though the association between orders and products is defined.
Calling only $orders = $this->Orders->find('all')->contain(['Products'])->all(); does return an array of orders with each order a number of products, the model has to be set up correctly. Any ideas what might be wrong? Thanks in advance!
From OrdersTable:
$this->belongsToMany('Products', [
'foreignKey' => 'order_id',
'targetForeignKey' => 'product_id',
'joinTable' => 'orders_products'
]);
And from ProductsTable:
$this->belongsToMany('Orders', [
'foreignKey' => 'product_id',
'targetForeignKey' => 'order_id',
'joinTable' => 'orders_products'
]);
One way to do it:
$orders = $this->Orders->find()
->select([
'order_id' =>'orders.id',
'price_sum' => 'SUM(products.price)'
])
->leftJoin('orders_products', 'orders.id = orders_products.order_id'),
->leftJoin('products', 'orders_products.product_id = products.id')
->group('orders.id');

CakePHP: difference between backtick query and normal query

I have 3 blog tables in my CakePHP application that are linked with a HABTM association following the CakePHP naming conventions: posts - post_tag_links - tags.
I try to get an array with all the posts that are linked to a specific tag (e.g. "design"). This query works for me:
$this->Post->query("
SELECT
Post.id, Post.title FROM posts AS Post
LEFT JOIN
post_tag_links AS PostTagLink ON Post.id = PostTagLink.post_id
LEFT JOIN
tags AS Tag ON Tag.id = PostTagLink.tag_id
WHERE
Tag.slug = 'design'
GROUP BY
Post.id"
);
CakePHP then generates the following query and gave me 4 results:
SELECT
Post.id,
Post.title
FROM
posts AS Post
LEFT JOIN
post_tag_links AS PostTagLink
ON Post.id = PostTagLink.post_id
LEFT JOIN
tags AS Tag
ON Tag.id = PostTagLink.tag_id
WHERE
Tag.slug = 'design'
GROUP BY
Post.id
BUT... to do some best practice, it's better to not use the "query" method. So I tried the "find all" method:
$this->Post->find('all', array(
'fields' => array(
'Post.id',
'Post.title'
),
'joins' => array(
array(
'table' => 'post_tag_links',
'alias' => 'PostTagLink',
'type' => 'LEFT',
'conditions' => array(
'Post.id' => 'PostTagLink.post_id'
)
),
array(
'table' => 'tags',
'alias' => 'Tag',
'type' => 'LEFT',
'conditions' => array(
'Tag.id' => 'PostTagLink.tag_id',
)
)
),
'conditions' => array(
'Tag.slug' => 'design'
),
'group' => 'Post.id'
)
));
CakePHP then generates the following query and gave NO single result:
SELECT
`Post`.`id`,
`Post`.`title`
FROM
`kattenbelletjes`.`posts` AS `Post`
LEFT JOIN
`kattenbelletjes`.`post_tag_links` AS `PostTagLink`
ON (
`Post`.`id` = 'PostTagLink.post_id'
)
LEFT JOIN
`kattenbelletjes`.`tags` AS `Tag`
ON (
`Tag`.`id` = 'PostTagLink.tag_id'
)
WHERE
`Tag`.`slug` = 'design'
GROUP BY
`Post`.`id
After a lot of trial and error, I discovered the problem is the backticks that CakePHP creates when building up that last query.
My question is: what's the difference between the query with the backticks and the one without the backticks? And how can you leave those backticks in CakePHP?
Thanks ;)
The backticks most probably aren't the problem, as all they do is escaping the identifiers. This is a pretty easy find btw.
http://dev.mysql.com/doc/refman/5.7/en/identifiers.html
Using backticks around field names
The actual problem is more likely that you've defined the conditions in the wrong way, what you are doing there is creating string literal comparision conditions, ie
`Post`.`id` = 'PostTagLink.post_id'
Comparing the id column value to the string PostTagLink.post_id will of course fail.
The correct way to define identifier comparisons is to supply the conditon fragment as a single value instead of a key => value set, ie
'conditions' => array(
'Post.id = PostTagLink.post_id'
)
and
'conditions' => array(
'Tag.id = PostTagLink.tag_id'
)
See also
Cookbook > Models > Associations: Linking Models Together > Joining tables

Mysql Join rows from multiple tables

I am asking here because what english words i need to search for this what i want to do.
I can solve this with multiple queries then join arrays with for and foreach loops but why to do it if there is smarter way.
My query now looks like:
SELECT p.* , pi.path, pv.videoid
FROM products p
JOIN productimage pi ON (p.id = pi.product)
JOIN productvideo pv ON (p.id = pv.product)
WHERE p.id=:id
my tables look like
product:
|---id---|---name----|---desc---|---price---|---active----|
|---1----|---somet---|---dsa----|---456-----|---1/0-------|
|---2----|---somet2--|---ddsasa-|---44556---|---1/0-------|
product video:
|----id----|---product----|----videoid-------|
|----4-----|---1----------|-----youtubeid----|
|----4-----|---1----------|--secondyoutubeid-|
and same as video for images, and i want to make same for files
result like this to make it easy
//result of $stmt->fetchAll(PDO::FETCH_ASSOC);
$arr = array(
0 => array(
"id" => "1",
"name" => "hello world",
"category" => "3",
"videoid" => array("oneyoutubeid", "secondid", "thirdid"), //videos that is for this product
"path" => array("imagepathofproduct", "secondimageofproduct"),
"active" => "1"
),
1 => array(
"id" => "2",
"name" => "hello world product 2",
"category" => "4",
"videoid" => array("oneyoutubeid", "secondid", "thirdid"), //videos that is for this product
"path" => array("imagepathofproduct", "secondimageofproduct"),
"active" => "1"
),
);
to use it like this: return $stmt->fetchAll(PDO::FETCH_ASSOC); and start foreach for displaying data.
thankyou very much
solved by concat and i will explode it into array.
but still waiting for more smart solutions.
Solution:
SELECT p.* , GROUP_CONCAT(DISTINCT path ORDER BY pi.id) AS images, GROUP_CONCAT(DISTINCT videoid ORDER BY pi.id) AS videos FROM products p JOIN productimage pi ON (p.id = pi.product) JOIN productvideo pv ON (p.id = pv.product) WHERE p.id=1
Home it will helpt to somebody

CakePHP model associations - Random order on retrieve of associated model for HABTM

I am retrieving data:
$mydata = $this->ProductList->find('all', array('order' => 'rand()', 'conditions' => array('name' => 'we love')));
I have set up a HABTM relationship to the Product model. As you can see, I am fetching all products in the 'we love'-list. Now, I want those Products I am retrieving to be randomised. But they are not, instead the MySQL is randomised on the ProductList model as you can see in the SQL. Why is that? How can I get the random fetch on the Products instead?
Resulting MySQL query:
SELECT `ProductList`.`id`, `ProductList`.`name` FROM `database`.`product_lists` AS `ProductList` WHERE `name` = 'we love' ORDER BY rand() ASC
SELECT `Product`.`id`, `Product`.`category_id`, `Product`.`name`, `Product`.`price`, `Product`.`description`, `ProductListsProduct`.`product_list_id`, `ProductListsProduct`.`product_id` FROM `database`.`products` AS `Product` JOIN `database`.`product_lists_products` AS `ProductListsProduct` ON (`ProductListsProduct`.`product_list_id` = 3 AND `ProductListsProduct`.`product_id` = `Product`.`id`)
EDIT:
There are so many different ways to approach this; to get a random product from a user's product list. You could do it with PHP - just find all of the products and then use rand() to pick on from the returned array. You could set a Model query condition. The list goes on...
I would probably create an alias to the Product model in ProductList called RandomProduct. You could set the query for the retrieved product when you set the relationship:
public $hasMany = array(
'RandomProduct' => array(
'className' => 'Product',
'foreignKey' => 'product_list_id',
'order' => 'Rand()',
'limit' => '1',
'dependent' => true
)
);
You can then use the containable behavior so that this model is only retrieved when you need it. (You wouldn't need to do this if recursive finds are greater than -1, but I usually do that as best practice so that my models only query for the data that they need.) The following would return any ProductList called 'we love' and a "random" product associated with that list.
$mydata = $this->ProductList->find(
'all',
array(
'conditions' => array(
'name' => 'we love'
)
),
'contain' => array(
'RandomProduct'
)
);