Hello i have question about Yii2 has many.
My table structure :
-------------------------
----col1------col2-------
------3---------4--------
------4---------1--------
and now i have method in my Model class:
getCols(){
return $this->hasMany(Cols::className,['col1'=>'id']);
}
and now i want to get all records where for example col1 = 4 or col2 = 4, so how can i set or statement ? I know that i can do
getCols(){
return $this->hasMany(Cols::className,['col1'=>'id','col2'=>'id']);
}
but this method returns me records for example where col1 = 4 AND col2 = 4
Greetings
If i understand you correctly.
getCols(){
return $this->hasMany(Cols::className(), ['col1' => 'id'])
->orOnCondition(['col2' => 'id']);
}
Please confirm in the comment if it works.
REF1 : How to use constant in the ON condition in Yii2 hasMany relation
REF2 : http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#orOnCondition()-detail
Related
I have a column called type that the value could be an object as a string, for example:
type = "{ 'a' : 'test1', 'b' : 'test2' }";
I want to get using Eloquent all rows where type.b = "test";
I can't access b in my where statement as it's not a column variable. I know I can use regex for it but I want to see if there is a better approach.
You should add "casts" in your Model like this
protected $casts = [
'type' => 'array'
];
And after it you can access b like this
$model->type['b'];
I have two tables: (Table A & TableB).
Table A = id(primary), name, email
Table B = user_id(foreign(id)), column1, column2
What I need to do is:
Insert a row in Table A.
Verify the insertion.
Insert row in Table B & store Table A (id) in Table B (user_id).
Currently, I'm handling it like the following.
// Create a row in Table A
$createUser = UserModel::create($userData);
// Verifying insertion of the by checking if id is set
if (isset($createUser['id'])) {
$adminData = [
'name' => $info['adminName'],
'user_id' => $createUser['id'], // insert into user_id
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
];
$createAdmin = AdminsModel::create($adminData);
}
I'm looking for a better way for multiple chained tables to avoid an if-else ladder.
There is nothing wrong with what you are doing. But you can also use eloquent relationships.
First define this method in the UserModel.
/**
* Get the admin associated with the user.
*/
public function admin()
{
return $this->hasOne(AdminsModel::class);
}
And use it like so
$createUser = UserModel::create($userData);
$createUser->admin->create([
'name' => $info['adminName'],
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
]);
If you get the following code :
$DBConnection =
CreateNewDBConnection(Yii::$app->get('db_cdh'),$aDatabaseName);
$DBConnection->open();
$command = $DBConnection->createCommand($aQuery);
$queryres = $command->queryAll();
If there is result from the query, I get an array, like this
Array
(
[0] => Array
(
[name] => 2.6.084.545
[xdim+2] => 70
)
[1] => Array
(
[name] => 2.5.102.030
[xdim+2] => 60
)
[2] => Array
(
[name] => 2.5.141.560
[xdim+2] => 80
)
)
But if the result of the query is empty, i get an empty array.
How is it possible to get the columns name ?
The reason why I'm asking this, it's because I'm asking queries to multiple DBs and some have results (1 or more lines) and otherd not. The system almost works, but the grid view parse only the first line to find the columns to display. So depending on the order result across the multiple DB, the grid view display the columns or not, depending what come first ....
Any help welcome.
You can take the column names using yii\db\TableSchema and use them afterwards:
$columns = [];
if (empty($queryres)) {
$columns = $DBConnection->getTableSchema('your_table_name')->getColumnNames();
}
I have a field in database. It's type is enum and it looks like
enum('NO ANSWER', 'ANSWERED', 'BUSY').
I need to put this values into dropdown. How can I write query in cakephp?
I tried:
$result = TableRegistry::get('Calls')->find('list', ['valueField' => 'disposition'])->distinct('disposition')->toArray();
But it returns
[
(int) 1 => null,
(int) 77 => '',
(int) 64 => 'NO ANSWER',
(int) 65 => 'ANSWERED',
(int) 72 => 'BUSY'
]
but I need something like this:
[
(int) 1 => 'NO ANSWER',
(int) 2 => 'ANSWERED',
(int) 3 => 'BUSY'
]
I need to put this values into dropdown
Unless the enum values are going to change frequently (and if the are, why would you use an enum..) just put the array of data you need somewhere:
$options = [
'NO ANSWER' => 'NO ANSWER',
'ANSWERED' => 'ANSWERED',
'BUSY' => 'BUSY'
];
And then use it:
echo $this->Form->select('field', $options);
Note that the key in $options is what will be submitted, the value is what will be displayed. More info about the select method is in the documentation.
I found this answer somewhere on SO, but I couldn't find it again. You can do this:
$cols = $this->Model->query("show columns from table_name like 'enum_column_name'")
$enum = explode(',', substr(str_replace(array("'", "(", ")"),'',$cols[0]['COLUMNS']['Type']), 4));
$options = array_combine($enum, $enum);
Then in your form, you can use the end of AD7six's answer and add:
echo $this->Form->select('field', $options);
The problem is that the values of enum are defined in the create table, they are not a piece of data available when you query your table's data. How can I get enum possible values in a MySQL database? SO topic describes how to get the values of the enum through a php code. Just make sure that you reassign the keys for the enum values so that the keys start from 1, and not from 0 (0 stands for empty value).
i'm thinking about this for days now and don't come to grasps (since i'm relativley new to MVC and CI). I'm not even sure whether this is an issue with MVC, MySQL or arrays.
Situation: 2 MySQL tables
Table data: id, title, list
Table values: id, name
Querying the data table results in an array like the following (excerpt):
[4] => Array
(
[id] => 3
[title] => Foo
[list] => 1,2,3,4,6,14
)
[5] => Array
(
[id] => 4
[title] => Bar
[list] => 2,6,9,12
)
The field list contains comma separated values that correspond to some IDs of the values table like
[3] => Array
(
[id] => 12
[name] => 'value12'
)
What I try to do for each row is:
take the list-values & explode it into an array
check with the result set from the values-table (via in_array() method)
return the name values of the IDs if
include it somehow into the main result set (e.g. as a 2-dimensional array):
[5] => Array (
[id] => 4
[title] => Bar
[list] => Array (
[0] => value6
[1] => value12
...
)
)
My naive approach so far was to
run a query on each of the 2 tables
compare the 2 result sets via in_array
My main problem (while trying to strictly separate model, controller and view): How can I include the name field from the values-table in the "main loop" of the data table result set?
if($q->num_rows() > 0)
{
$data[] = $q->result_array();
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
If I use the following (cumbersome) approach i naturally get a new item each time:
foreach ($q->result_array() as $row)
{
$data[]['id'] = $row['id'];
$data[]['title'] = $row['title'];
$data[]['list'] = $row['year'];
}
Since this is a MySQL database I see no way to do the explode and the comparison in SQL (with LIKE or something else).
Any hint, even a simple link to an info bit, is highly appreciated.
Thanks a trillion!
fab
There is a many-to-many relationship between lists and list values. The conventional way to model this in a relational database is to create a joining table. So I'd structure your schema like this.
lists : list_id, title
values : value_id, name
list_values : list_id, value_id
list_values is the joining table. It links lists with values.
To build a list you could have the following functions in your model
function build_list($list_id)
{
$list = $this->get_list($list_id);
$list->values = $this->get_list_values($list_id);
return $list;
}
function get_list($list_id)
{
$sql = 'select * from lists where list_id=?';
return $this->db->query($sql, array($list_id))->row();
}
function get_list_values($list_id)
{
$sql = 'select v.value_id, v.name
from list_values lv
join values v on v.value_id=lv.value_id
where lv.list_id=?';
return $this->db->query($sql, array($list_id))->result();
}