How to connect two different DB tables using Cakephp? - php

convert following query into cakephpquery.
"SELECT * FROM user1.user_favourites,esl.esl_lyrics
WHERE
esl_lyrics.id=user_favourites.fav_recordID
AND user_favourites.fav_userID=".$user_id."
AND user_favourites.fav_widgetID=$wid_id";
Models files are esl.php and userFavourite.php
DB are user1 and esl.
DB tables are user_favourites in user1 and esl_lyrics in esl DB.
plz give details.what changes are do in esl.php and userFavourite.php
please Help me...

It will be difficult to determine what to write until you can provide a data map for the various IDs you are using. Since you are not conforming to standards in your SQL, the fields are all named different in the various tables. But here is what I understand so far:
esl_lyrics.id = user_favorites.fav_recordID
From your description there are two models. So you will need to make sure you have relationships between the two. This will require that you determine if it is belongsTo, hasOne, hasMany, etc.
It also appears you are using multiple databases (schemas), so you will need to configure the database.php so that you can access each one.
Once everything is configured you should be able to access the data as:
$this->Model1->Model2->find('all', array('conditions' => array('Model1.id' => 'Model2.id', 'Model2.user_id' => $user_id, 'Model2.widgetID' => $wid_id)));
It will return an array with the data from both models. But until you can share what your models look like and a mapping of ids etc., this will be as good of an answer as you will get.

Related

is it advisable to use polymorphic relations with joins?

I've created migrations and also their relationships. looks like I'm using polymorphic relations, because in one table, I could have the value of one model or i could have the value of another model. as you might guess, I have something like this
ID Mappable_type Mappable_id value
Mappable_type could be one or many other models. mappable_id will be appropriate id from that model. I needed this because I'm creating dynamic form builder and that's how I designed a database.
Now I need to fetch some records from 5 tables together, so I gotta use joins. the table where I have mappable_type is at the third place from those 5 joins. now What should I do also to only fetch data from these 5 joins that have specific model type that is in that morph table? I'm doing something like that for now:
$final = Dynamic::join('dynamic_properties_values','dynamic_properties_values.dynamic_id','=','dynamic.id')
->join('dynamic_properties_mapping','dynamic_properties_mapping.id','=','dynamic_properties_values.mapping_id')
->where('dynamic_properties_mapping.mappable_type','=','App\Driver')
->get();
As you see, I have written by hand something like
"App\Driver"
. It doesn't matter I have written it by hand or had it saved into a variable and than used it here. WHat really bothers me is that let's say when I was inserting data into these morph tables, Model got saved as "App\Driver". what if I make a mistake and when fetching with joins, I write something like App\Http\Driver? or what If I changed the location of the model itself in my code project?
What's the best practice not to make those kind of errors by the time my project reaches huge amount of users?

How can I set associations between models in Cake PHP 3.5?

I have a db structure like this in MySql. And I use Cake PHP 3.5.
I wolud like to add to table1 a belongsToMany connection to table4. And add its inverse to table4 too.
$this->belongsToMany('Table4', /*What goes here*/);
And what is for table4?
Can I make this Join with a finder in the belongsToMany?
Thanks!
As ndm said in comments Cake does not suport what you want to do, just for a reason, this is not a many to many relation, please create you database by migrations, first of all https://book.cakephp.org/3.0/pt/migrations.html after that (bake migration, execute migration) your database will exist, the you can run a bake for create models, then you will realize that you can build a query like
$this->table1->table2->table3->table4->find()->where([conditions]);
or another like
$this->table1->find()->contain(['table2' => ['table3' => ['table4' => 'conditions' => ['RealConditions']]]])->first();
If you don't want to learn all of this you can go throught the paintfull path. Or just read about it first https://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations

Is it possible to join two query result with PHP code?

I need to JOIN 2 tables (lets say User & Order table) for reporting module in my web app.
The problems are:
The User table is located on the different server & different
DBMS from the Order table. Technically it is a different system, so the User table is located on SQL Server DB, meanwhile the Order table is located on MySQL DB.
I couldn't use SQL Server's Linked Server because my company policy doesn't allow it. So, I coudn't JOIN them directly with SQL code. They want me to use Web Service instead of linked server.
The result of JOIN operation from those tables has a large number of rows (maybe more than 10,000 rows because the data aimed for reporting). So, I think it was a horrible thing to mapping them using Web Service.
So I came up with this:
I collected 2 query result from different models and join them with my app code (I'm using PHP with CodeIgniter) :
// First result
$userData = $this->userModel->getAllUser();
// Second result
$orderData = $this->orderModel->getAllOrder();
The $userData contains all user entities with the following columns:
[UserId, Username, Address, PhoneNumber, etc..]
And the $orderData contains all order entities with the following columns:
[OrderId, UserId, Date, etc..]
But is it possible to join those two query results in PHP / CodeIgniter?
How about the performance regarding the large amount of data?
Should I just use Web Service as suggested or there's another solution to accomplish this?
Thanks in advance :)
A few things to think about:
Do you actually need to return all user and order records in one single go
Do you actually want to return all rows for these two types of record
Would you be better off with a Report module for these report queries?
Would plain SQL syntax be a smarter move than trying to shim this into existence with the CodeIgniter "Active Record" (renamed Query Builder in 3.0)
Is JOIN really so bad? It is not a UNION, you want the data to be related.
I would recommend you limit your data returns, SELECT only the fields you actually require, make a new Report model to avoid trying to mess up your generic models and do this with raw SQL.
Complicated things get all the more complicated when you try too hard to stick to rules like "1 table = 1 model" and "User::getAllFoos + controller processing > Report::getMonthlyOrderStats()".

How do I get the comment of a specific column with Doctrine ORM

Is there a way to retrieve the column's comment (like from INFORMATION_SCHEMA.COLUMN table on MySQL) from a certain table without actually "hardcode" the query with Doctrine ORM?
Finally I found an way. what I was trying to do was get a column comment from inside a Controller
//lets say we have a table named 'product'
//and we want to get the comment from the 'name' column
//first we get a list of columns from 'product'
$columns = $this->getDoctrine()->getEntityManager()->getConnection()->getSchemaManager()->listTableColumns('product');
//then we just access getComment function from the 'Column' class
//for the 'name' column:
echo $columns['name']->getComment();
I doubt it, and the same would go for Propel as well. Both use PDO, and afaik there is no database-neutral way to do this.
To achieve this, you can often query the table columns using SELECT statements on system tables (certainly Oracle and PostgreSQL allow this). However, the names of the tables involved differ from one vendor to another. Here is how to get column names, for example, in PostgreSQL - getting comments would probably be quite similar.
It would be quite possible for an ORM to offer what you want, but the underlying implementation would be the approach I outline above. Perhaps you could request it on the Doctrine mailing list?

How do I get results from a database table based on results from a different table in cakephp?

For example I have the following tables in my database:
People
Groups
And in the People table I have the following columns:
Name
Birthdate
Group
In the Groups table I have the following columns:
Name
Colour
Now I want to fetch results from my database to make a list of all the People.
So I would use this:
$this->set('people', $this->Person->find("all"));
And obviously in my view I would loop through the returned array and display it. Now I also want to find out for each person in the list what Colour and Group name they are (retrieved from the groups table).
How would I go about this in CakePHP.
First make sure your model relationships are defined. Second, you might want to consider using "id" fields for your related tables (I assume you did and maybe just did not include them in your original questions table definitions).
And yes, run debug($this->Person->find("all")) as Elwhis noted to see what your array is dumping out.
And if this is a mission critical application, be sure to use containable instead of recursive to prevent taxing queries to your db.
You have to set the recursive attribute. But I guess it should work with the default value. Put this line in your controller debug($this->Person->find("all")) and check whether the data doesn't already contain you desired group information.
If not, try setting $this->Person->recursive = 1; before calling the find() function
For more information about recursive: http://book.cakephp.org/view/1063/recursive

Categories