Laravel、mysql 查询并加入模型 class

Laravel, mysql query with join in model class

laravel 为每个 table 创建自己的模型。由于它是最受欢迎的框架之一,因此我们选择了它。我们的大多数 mysql 查询都基于多个 tables,我们使用 join 并在控制器本身中编写这些查询。有人能告诉我们如何处理模型 class 中的多个 table 的查询吗?

提前致谢。

您必须在模型中定义关系 class,有关关系的信息请参阅 here

例如如果我想访问州名称,请在我的城市页面中:

Controller:

$city = App::make('Platform\Storage\City\CityRepository')->view($city_id, false, [], ['state'=>array('id', 'name')])

Repository:

public function view($id, $active=true, $fields=array(), $with=array()) {
        $query = $this->model->newQuery();
        $tableName = $this->model->getTable();

        if ($active) {
            $query->where($tableName . '.is_active', '=', 1);
        }
        if (!$fields) {
            $fields = array($tableName . '.*');
        }
        if ($with) {
            $with = $this->model->processWithSelects($with);
            $query->with($with);
        }

        try {
            return $query->with($with)->where($tableName . '.id', '=', $id)->first($fields);
        }
        catch (Exception $e) {
            throw new DBException($e->getMessage(), $e->getCode(), $e->getPrevious());
        }
    }

City Model:

public function state() {
    return $this->belongsTo('State');
}

有关详细信息,请访问这些:Tutorial on Repository, Laravel Query, Simple CRUD

In your Controller, create a constructor:

public function __construct(Model $model) {
    parent::__construct();

    $this->model = $model; // Model $model, means IOC or Dependancy Injection
    }

然后执行:$this->model->function_in_your_model(),以执行您的模型功能。

看看,是否有帮助。