【问题标题】:Yii2 Active record working: How i can query through relation in yii2 modelYii2 活动记录工作:我如何通过 yii2 模型中的关系进行查询
【发布时间】:2016-05-20 10:41:26
【问题描述】:

这是我的餐厅模型:

class Restaurents extends \yii\db\ActiveRecord
{
    public function rules(){
        return [
            [['name'], 'string'],
        ];
    }
    public function getRestaurentInfo(){
        return $this->hasOne(RestaurentInfo::className(), ['restaurent_id' => 'id']);
    }
}

和我的 RestaurentInfo 模型:

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。

我该怎么做?

【问题讨论】:

    标签: yii2 active-record-query


    【解决方案1】:

    你可以这样做:

    $restaurents = Restaurent::find()
        ->joinWith('restaurentInfo')
        ->where(['like', 'name', $key])
        ->orWhere(['like', 'address', $key])
        ->all();
    

    我建议花一些时间了解如何使用 Active Record 和 Active Query。

    【讨论】:

    • 谢谢。我也试过了,但返回的结果不是我需要的。我想查询名称如 $key 或地址如 $key 的餐馆列表。我该怎么做
    • @DuyMuu 此代码完全按照您的数据结构进行描述。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多