ziv*_*rah 2 php search activerecord foreign-keys yii
在我的数据库中,我有两个表,制造商和塑料:
CREATE TABLE `manufacturer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8
CREATE TABLE `plastic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL DEFAULT '',
`manufacturer_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`,`manufacturer_id`),
KEY `manufacturer_id` (`manufacturer_id`),
CONSTRAINT `plastic_ibfk_1` FOREIGN KEY (`manufacturer_id`) REFERENCES `manufacturer` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,塑料具有Yii称之为与制造商的BELONGS_TO关系 - 一个制造商可以制造几种不同的塑料.
我试图通过默认塑料管理页面中的制造商名称进行搜索,但搜索字段不会显示在"制造商"列中.我遵循了这个指南,我想我差不多了,但是我被困在一个小细节上.
在我的Plastic模型类中,根据上面的链接,我有:
class Plastic extends CActiveRecord
{
public $manufacturer_search; //<-- added per the above link
public function rules()
{
return array(
array('manufacturer.name', 'length', 'max'=>64),
array('name', 'length', 'max'=>64),
array('name, manufacturer.name, manufacturer_search', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'manufacturer' => array(self::BELONGS_TO, 'Manufacturer', 'manufacturer_id'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with=array('manufacturer');
$criteria->compare('name',$this->name,true);
$criteria->compare('manufacturer.name',$this->manufacturer_search, true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Run Code Online (Sandbox Code Playgroud)
}
管理页面使用CGridView小部件来显示所有内容(这是默认设置,除了'columns'属性之外我没有更改任何内容):
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'plastic-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'name',
'manufacturer.name',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Run Code Online (Sandbox Code Playgroud)
令人抓狂的是,搜索确实有效:如果我点击高级搜索,并在制造商字段中输入内容,那就有效.但我不能为我的生活使搜索框显示在网格视图中.
以下是一些屏幕截图:当我将manufacturer_id传递到窗口小部件时的管理页面的屏幕截图,当我通过manufacturer.name时的屏幕截图,如上面的代码,当我通过manufacturer_search时的屏幕截图(我没想到它会工作) ,最后高级搜索的截图正常工作.
有任何想法吗?谢谢.
您必须filter专门为以下内容创建$manufacturer_search:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'plastic-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'name',
array(
'name'=>'manufacturer.name',
'filter'=>CHtml::activeTextField($model,'manufacturer_search'),
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6743 次 |
| 最近记录: |