【发布时间】:2018-06-07 14:55:52
【问题描述】:
我已经阅读了所有 Yii2 框架文档,但是在尝试实现它时感到困惑。
我有一个客户视图,它显示了客户表中的所有字段,包括地址表中的address_id 字段。
我想在 Yii2 框架中使用 MySQL 实现一个连接查询,但生成的代码如下:
模型中的客户搜索:
class CustomerSearch extends Customer{
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['customer_id', 'store_id', 'address_id', 'active'], 'integer'],
[['first_name', 'last_name', 'email', 'create_date', 'last_update'], 'safe'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Customer::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'customer_id' => $this->customer_id,
'store_id' => $this->store_id,
'address_id' => $this->address_id,
'active' => $this->active,
'create_date' => $this->create_date,
'last_update' => $this->last_update,
]);
$query->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'email', $this->email]);
return $dataProvider;
}
客户类别:
class Customer extends \yii\db\ActiveRecord{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'customer';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['store_id', 'first_name', 'last_name', 'address_id'], 'required'],
[['store_id', 'address_id', 'active'], 'integer'],
[['create_date', 'last_update'], 'safe'],
[['first_name', 'last_name'], 'string', 'max' => 45],
[['email'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'customer_id' => 'Customer ID',
'store_id' => 'Store ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'address_id' => 'Address ID',
'active' => 'Active',
'create_date' => 'Create Date',
'last_update' => 'Last Update',
];
}
}
【问题讨论】:
-
你想加入什么?您必须有另一个表和模型并定义关系。您是否使用 Gii 模型/CRUD 生成器生成了此代码?
-
表Customer和表Address使用公共字段'address_id'
-
啊,是的,我错过了,抱歉。你用过 Gii 模型/CRUD 生成器吗?
-
是的,CRUD 生成器
标签: php mysql activerecord yii2 foreign-keys