我在Laravel待了五天,经过几个小时的观看Jeffrey Way后,我决定深入研究构建应用程序以便学习。
我陷入了处理hasManyThrough布局中的表并确定表之间的链接的列。 Eloquent正试图使用名为“id"作为它无法找到的主键。在我的表中,我使用命名约定tablename_id,如下所示。在我的类函数中,我指定要使用的列,但它失败并显示错误:
QueryException in Connection.php line 620:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cable_installations.id' in 'on clause' (SQL: select `cable_specifications`.*, `cable_installations`.`cable_specifications_id` from `cable_specifications` inner join `cable_installations` on `cable_installations`.`id` = `cable_specifications`.`cable_installations_id` where `cable_installations`.`cable_specifications_id` is null)
我正在尝试检索:
所选cable_installation_method
允许的电缆规格清单谢谢!
表1:cable_specifications
cable_specifications_id (REPEATS)
other_columns...
表2:cable_installation_methods
cable_installation_methods_id (UNIQUE)
other_columns...
表3:cable_installations(PIVOT)
cable_specifications_id (REPEATS)
cable_installation_methods_id (REPEATS)
我的课程是:
use Illuminate\Database\Eloquent\Model as Eloquent;
class CableInstallationMethod extends Eloquent {
protected $table = 'cable_installation_methods';
protected $fillable = [];
public function CableInstallation()
{
return $this->hasMany('CableInstallation');
}
public function CableSpecByInstall()
{
return $this->hasManyThrough('App\CableSpecification', 'App\CableInstallation', 'cable_specifications_id', 'cable_installations_id');
}
}
在我的控制器中,我按下面的说法调用此功能:
public function VoltageDropLoad()
{
$InstallationMethods = CableInstallationMethod::all();
$CableSelected = CableInstallationMethod::where("cable_installation_methods_id", 1)->first();
$CableTypes = $CableSelected->CableSpecByInstall()distinct()->get()->toJson();
return view('pages.voltcalc', compact('InstallationMethods', 'CableTypes', 'CableTypes'));
}
答案 0 :(得分:1)
根据您的CableInstallationMethod类,您可能错过了为模型定义主键字段的信息:
use Illuminate\Database\Eloquent\Model as Eloquent;
class CableInstallationMethod extends Eloquent {
protected $table = 'cable_installation_methods';
/* Need to define $primaryKey column here, normally defaults to 'id' */
protected $primaryKey = 'cable_installation_methods_id';
protected $fillable = [];
public function CableInstallation()
{
return $this->hasMany('CableInstallation');
}
public function CableSpecByInstall()
{
return $this->hasManyThrough('App\CableSpecification', 'App\CableInstallation', 'cable_specifications_id', 'cable_installations_id');
}
}
使用主键设置,您还可以利用Model :: find($ id)而不是使用Model:where(...) - > first()
public function VoltageDropLoad()
{
$InstallationMethods = CableInstallationMethod::all();
$CableSelected = CableInstallationMethod::find(1);
$CableTypes = $CableSelected->CableSpecByInstall()->distinct()->get()->toJson();
return view('pages.voltcalc', compact('InstallationMethods', 'CableTypes', 'CableTypes'));
}