我想在字段" table_ids"中保存数组数据(json数据)。表2,例如:
TABLE_1
| id | name |
----------------
| 1 | title 1 |
| 2 | title 2 |
| 3 | title 3 |
| 4 | title 4 |
etc...
TABLE_2
| id | table_ids |
---------------------
| 1 | "{1,3}" |
| 2 | "{3,4,2}" |
并且,我很感兴趣如何在表2的Phalcon模型中建立关系,hasMany as" table1relation"表1中的字段" table_ids"
$this->hasMany( 'table_ids', 'Table1', 'id', array('alias' => 'table1relation' ));
以便在Table_2中具有正确绑定的对象
$tbl2 = Table2::find();
foreach( $id in $tbl2.table1relation ) {
echo $id->name;
};
我想知道这可能吗? 感谢
答案 0 :(得分:0)
第一个有效的解决方案是:
class Table2 extends Model
{
....
// get all items with mapped Table1 model resulsets
public static function GetItems() {
$items = Table2::find()->filter( function( $current_item ){
if ( $current_item->table_ids != null ) {
$final = array();
$array = explode( ",", $current_item->table_ids );
foreach( $array as $key => $value ) {
$table1_item = Table1::findFirst($value);
array_push( $final, $table1_item );
}
$current_item->table_ids = $final;
} else {
$current_item->table_ids = array();
}
return $current_item;
});
return $items;
}
public function beforeSave() {
if ( is_array( $this->table_ids ) ){
$cat_value = "";
$ids = $this->table_ids;
foreach( $ids as $ids_item ) {
$cat_value .= $ids_item->id;
if ( next( $ids ) == true ) $cat_value .= ",";
}
$this->table_ids = $cat_value;
}
}
}
现在我们可以在控制器中使用这样的方法
// get items
$items = Table2::GetItems();
foreach( $items->table_ids as $ids ) {
echo $ids->name;
}
...
$ids = new Table1();
$ids->id = 6;
$ids->name = "title 6"
$item = new Table2();
$item->id = 10;
$item->table_ids = $ids;
// or
$item->table_ids = "1,2,3,4,5";
这项工作