I have joined with two table by using model association. This two tables are films and movie_streams But there is some error
My Query:
$film = Film::model()->with('movie_streams')->find(array('select' => '*', 'condition' => 'user_id=:user_id, 'params' => array(':user_id' => $user_id)));
Film.php model:
public function relations() {
return array(
'movie_streams' => array(self::HAS_MANY, 'MovieStream','movie_id'),
);
}
Error Message:
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'user_id' in where clause is ambiguous
I saw by default taking alias name. For films table t and for movie_streams table t0
How to set manual alias what I want for my above two tables?
You can avoid the collision of tables aliases by specifying the alias property of the relation.
$comments = Comment::model()->with(array(
'author',
'post',
'post.author' => array('alias' => 'p_author'))
)->findAll();
use
model_name.feild_name
$film = Film::model()->with('movie_streams')->find(array('select' => '*', 'condition' => 'film.user_id=:user_id, 'params' => array(':user_id' => $user_id)));
or
avoid collision of table by using allias
$comments=Comment::model()->with(array(
'author',
'post',
'post.author'=>array('alias'=>'p_author')))->findAll(array(
'order'=>'author.name, p_author.name, post.title'
));
, more details here
Related
I have Three tables Projects, Tasks and Tags. Projects.id is the primary key of the first table, Tasks.id is the PK of the second table and Tags.id is the PK of Third table.
$test = $this->Projects->find('all',
array(
'recursive' => 2
)
);
Returns right data.
But
$test = $this->Projects->find('all',
array(
'recursive' => 2,
'conditions' => array('Tags.id = ' => '10')
)
);
Gives below error.
Column not found: 1054 Unknown column 'Tags.id' in 'where clause'.
I do have id field for Tags table, Why getting this error?
Projects Model Code snippet
public $primaryKey = 'id';
public $hasMany = array(
'Tasks' => array('className' => 'Tasks','foreignKey' => 'project_id')
);
Tasks Model Code snippet
public $primaryKey = 'id';
public $hasMany = array(
'Tags' => array('className' => 'Tags','foreignKey' => 'task_id')
);
This is because you can not pass condition on hasMany associated Model fields.
To make this work, pass "joins" in the Find condition, this will work fine.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
I have a little problem with the displayField in combination with virtualFields.
I have a File that belongsTo 2 different Users.
public $belongsTo = array(
'Creator' => array(
'className' => 'User',
'foreignKey' => 'creator_id',
),
'Editor' => array(
'className' => 'User',
'foreignKey' => 'editor_id',
)
);
As virtualField and displayField in the User Model. I use the following code:
public $virtualFields = array(
'full_name' => "CONCAT(first_name, ' ',last_name)"
);
public $displayField = 'full_name';
Creating a new File works fine, but if I want to view all my files I get the following error:
Error: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'first_name' in field list is ambiguous
I already read about it a little here:
http://book.cakephp.org/2.0/en/models/virtual-fields.html
At the end there are some limitations about virtualFields, so I tried to add this to the Controller:
$this->virtualFields += $this->Creator->virtualFields;
$this->virtualFields += $this->Editor->virtualFields;
But somehow this doesn't change anything.
Hope you can help me with this little problem.
Thanks in advance!
I guess you need 2 virtual fields:
$this->File->virtualFields = array(
'Creator__full_name' => "CONCAT(Creator.first_name, ' ',Creator.last_name)",
'Editor__full_name' => "CONCAT(Editor.first_name, ' ',Editor.last_name)"
);
I have a habtm relation between questions and categories. This habtm relation is standard and setup in the respective models. I now have the following issue. In a controller action I have an array of several question ids. I want to return all of the categories that are linked to these questions. The find I am using looks as followed.
$case_questions_categories = $this->Category->find('all', array('conditions' => array('OR' => $case_question_id_array)));
// Here the $case_question_id_array is generated as followed:
foreach($question['CaseQuestion'] as $case_question) {
$case_question_id_array[] = "Category.question_id = " . $case_question['id'];
}
Its clear that this will not work, and it throws the following error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Category.question_id' in 'where clause'
SQL Query: SELECT `Category`.`id`, `Category`.`name`, `Category`.`slug`, `Category`.`category_order`, `Category`.`created`, `Category`.`modified`, `Category`.`is_deleted` FROM `streetofwalls`.`categories` AS `Category` WHERE `Category`.`question_id` = 182
This makes sense because the join table from the habtm relation is not referenced in the query I have generated. How do I get habtm relation to be properly handled so that I can pass a group of question ids and be returned the relevant categories.
Thank you to anyone who offers time or help.
Use a join
The kind of sql query you need to generate is:
SELECT
categories.* from categories
JOIN
categories_questions ON (categories_questions.category_id = categories.id)
WHERE
categories_questions.question_id IN (list, of, question, ids)
The simplest way to do that is to just use the join key in your query - this is also in the documentation.
Applied to the example in the question that'd be:
$ids = array()
foreach($question['CaseQuestion'] as $q) {
$ids[] = $q['id'];
}
$this->Category->find('all', array(
'conditions' => array(
'CategoriesQuestion.id' => $ids // You do not need an OR
),
'joins' => array(
array(
'table' => 'categories_questions',
'alias' => 'CategoriesQuestion',
'type' => 'inner',
'conditions' => array(
'Category.id = CategoriesQuestion.category_id'
)
)
)
));
I want to create in cake php application with users, games and games platforms (for ex PS3)
I got tables:
userGames (game have one platform)
id, name, platform_id
users (users can have many platforms)
id, username
platforms
id, name
users_platforms
id, platform_id, user_id
And now i want to select all user id=1 platforms, and list it for select tag.
Here is sql query:
SELECT platforms.name, platforms.id FROM platforms LEFT JOIN platforms_users ON platforms_users.platform_id=platforms.id WHERE platforms_users.user_id=1
But i dont know what to list this by find('list') function in cakePHP
I try type in users controller:
$this->User->Platform->find('list', array('conditions', array('User.id'=>'1')));
But this returns sql problem (undefinded User.id)
Anyone can help me?
please try this
$this->loadModel('UserPlatform');
$this->UserPlatform->bindModel(array(
'belongsTo' => array('Platform')
));
$this->UserPlatform->find('list', array(
'fields' => array('Platform.id','Platform.name'),
'conditions' => array('UserPlatform.user_id'=>'1'),
'recursive' => 1
));
you must apply find function on join table
Your find must same as this:
$this->PlatformUser->find('list',array('fields'=>
array('Platform.name','Platform.id'),'conditions'=> array('PlatformUser.id' => 1)));
Your PlatformUser Model must have:
public $belongsTo = array(
'Platform' => array(
'className' => 'Platform',
'foreignKey' => 'platform_id',
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
),
);
What you are trying to do is actually a HasAndBelongsToMany Association.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
hasAndBelongsToMany (HABTM)
We’ll need to set up an extra table in the database to handle HABTM associations. This new join table’s name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ ). The contents of the table should be two fields that are foreign keys (which should be integers) pointing to the primary keys of the involved models. To avoid any issues, don’t define a combined primary key for these two fields. If your application requires a unique index, you can define one. If you plan to add any extra information to this table, or use a ‘with’ model, you should add an additional primary key field (by convention ‘id’).
HABTM requires a separate join table that includes both model names.
(This would be the UserPlatform-table if I got that right.)
Make sure primary keys in tables cakes and recipes have “id” fields as assumed by convention. If they’re different than assumed, they must be changed in model’s primaryKey.
class Recipe extends AppModel {
public $hasAndBelongsToMany = array(
'Ingredient' =>
array(
'className' => 'Ingredient',
'joinTable' => 'ingredients_recipes',
'foreignKey' => 'recipe_id',
'associationForeignKey' => 'ingredient_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
)
);
}
I have a mysql table and a mysql view I'm trying to build relations for.
The table(commissions) is as follows:
--commissions--
id(primary Key)
date_added
order_id
salesrep_id
customer_id
commission_total
status
The view(rep_view_customer) is as follows:
--rep_view_customer--
entity_id
email
first_name
last_name
company
I'm trying to relate rep_view_customer to commissions on commissions.customer_id = rep_view_customer.entity_id.
I've tried using the on option:
'rep_view_customer' => array(self::HAS_ONE, 'RepViewCustomer', '', 'on'=>'rep_view_customer.entity_id = t.customer_id')
I also tried setting the primary key for the rep_view_customer model using:
public function primaryKey(){
return 'entity_id';
}
But I always seem to end up with an error similar to:
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 't.customer_id' in 'where
clause'. The SQL statement executed was: SELECT
rep_view_customer.entity_id AS t1_c0,
rep_view_customer.email AS t1_c1,
rep_view_customer.first_name AS t1_c2,
rep_view_customer.last_name AS t1_c3,
rep_view_customer.company AS t1_c4 FROM rep_view_customer
rep_view_customer WHERE (rep_view_customer.entity_id =
t.customer_id)
I'm at my wit's end what to try next
You will have to create a foreign key inside repview_customer to relate to commissions. You won't be able to do it with just a primary key.
I did it this way and it works:
so in the commissions model you put: (it does the relation through itself within the model, then the join output will be the same as the normal relation but with other unique key in commission model)
public function relations()
{
return array(
'commission' => array(self::HAS_ONE, 'Commission', 'entity_id', 'on' => 'commission.customer_id=rep_view_customer.entity_id'),
'rep_view_customer' => array(self::HAS_MANY, 'RepViewCustomer', '', 'through' => 'commission', 'condition' => '...'),
),
}