【发布时间】:2018-01-17 02:47:27
【问题描述】:
我想在 CRUD 中使用 Eloquent。此 CRUD 使用来自 4 个表的多个数据。
管理员:
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
语言:
Schema::create('langs', function (Blueprint $table) {
$table->increments('id');
$table->string('isocode', 10)->nullable();
$table->string('name', 80)->nullable();
$table->timestamps();
});
lang_sector:
Schema::create('lang_sector', function (Blueprint $table) {
$table->integer('lang_id')->index('FK_LANGS');
$table->integer('sector_id')->index('FK_SECTORS');
$table->integer('admin_id')->index('FK_ADMINS');
$table->string('name', 80)->nullable();
$table->string('shortname', 40)->nullable();
$table->text('description', 65535)->nullable();
$table->primary(['lang_id','sector_id']);
});
行业:
Schema::create('sectors', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
});
并在模型中设置关系:
- 一个部门属于一个管理员
- 一个管理员有很多部门
- 部门属于多种语言
- Lang 属于多个部门
在扇区模型中:
public function langs(){
return $this->belongsToMany('App\Lang')->withPivot('name','shortname','description');
}
public function Admin(){
return $this->belongsTo('App\Admin');
}
在语言模型中:
public function sectors(){
return $this->belongsToMany('App\Sector')->withPivot('name','shortname','description');
}
在管理员模式中
public function sectors(){
return $this->hasMany('App\Sector');
}
我想显示的信息可以用这个 SQL 请求来表示(更新版本):
SELECT DISTINCT
sectors.id,
lang_sector.sector_id,
lang_sector.lang_id,
lang_sector.admin_id,
langs.name,
lang_sector.name,
lang_sector.shortname,
admins.name,
admins.surname,
sectors.created_at,
sectors.updated_at
FROM lang_sector
INNER JOIN
langs ON langs.id = lang_sector.lang_id
INNER JOIN
sectors ON sectors.id = lang_sectors.sector_id
INNER JOIN
admins ON admins.id = lang_sector.admin_id
ORDER BY lang_sector.sector_id;
我的问题是:
- 如何在 Eloquent 中而不是在 RAW SQL 中“翻译”它...( $langs = Lang::latest('updated_at')->get();...)
- 我的另一个问题是我希望将登录的管理员作为值...
感谢您的帮助!
【问题讨论】:
-
我在您的
sectors表中没有看到admin_id列? -
另外,在您的 SQL 查询中,您加入了
sectors表,但实际上并没有使用该表做任何事情? -
我忘了更新 SQL ...
-
我修改了它......我今晚有点累了:))谢谢你的评论
-
鉴于您的 SQL 查询无法确认单个实体,我建议使用 DB 查询生成器而不是查询实体。或者,您可以查询实体并立即加载关系。
标签: laravel-5 eloquent laravel-eloquent