Yii2活动记录工作:如何通过Yii2模型中的关系进行查询
这是我的餐厅模式:Yii2活动记录工作:如何通过Yii2模型中的关系进行查询,yii2,active-record-query,Yii2,Active Record Query,这是我的餐厅模式: class Restaurents extends \yii\db\ActiveRecord { public function rules(){ return [ [['name'], 'string'], ]; } public function getRestaurentInfo(){ return $this->hasOne(RestaurentInfo::class
class Restaurents extends \yii\db\ActiveRecord
{
public function rules(){
return [
[['name'], 'string'],
];
}
public function getRestaurentInfo(){
return $this->hasOne(RestaurentInfo::className(), ['restaurent_id' => 'id']);
}
}
还有我的RestaureInfo型号:
class RestaurentInfo extends \yii\db\ActiveRecord
{
public function rules(){
return [
[['address',], 'string']
];
}
public function getRestaurent()
{
return $this->hasOne(Restaurens::className(), ['id' => 'restaurent_id']);
}
}
我想查询具有以下条件的餐厅列表:
餐厅的名称类似于$key,或餐厅的地址类似于$key
我怎么做?你可以这样做:
$restaurents = Restaurent::find()
->joinWith('restaurentInfo')
->where(['like', 'name', $key])
->orWhere(['like', 'address', $key])
->all();
我建议您花一些时间,了解如何使用和活动查询。您可以这样做:
$restaurents = Restaurent::find()
->joinWith('restaurentInfo')
->where(['like', 'name', $key])
->orWhere(['like', 'address', $key])
->all();
我建议您花点时间,了解如何使用和主动查询。谢谢。我也试过了,但返回的结果不是我需要的。我想查询一个名称为$key或地址为$key的餐厅列表。我该怎么办it@DuyMuu根据您的数据结构,此代码完全符合您所描述的内容。谢谢。我也试过了,但返回的结果不是我需要的。我想查询一个名称为$key或地址为$key的餐厅列表。我该怎么办it@DuyMuu根据您的数据结构,此代码完全执行您描述的操作。