我有以下关系:
折扣:
<?php
class Discount extends Eloquent {
protected $table = 'discount';
public $timestamps = true;
public function title()
{
return $this->hasOne('Translation', 'labelId', 'titleLabelId')->where('languageId', T::getLang())->first()['phrase'];
}
public function titles()
{
return $this->hasMany('Translation', 'labelId', 'titleLabelId');
}
}
?>
翻译:
<?php
class Translation extends Eloquent {
protected $table = 'translations';
public $timestamps = false;
protected $fillable = array('phrase', 'languageId', 'labelId');
public function language()
{
return $this->belongsTo('Language', 'languageId');
}
public function label()
{
return $this->belongsTo('Label', 'labelId');
}
}
?>
标签:
<?php
class Label extends Eloquent {
protected $table = 'label';
public $timestamps = false;
protected $fillable = array('key');
public function translations()
{
return $this->hasMany('Translation', 'labelId', 'id');
}
}
?>
共有三个数据库表,其中包含以下列:
折扣:
id |标题标签Id
翻译:
id |语言 ID |标签ID
标签:
ID
问题:我想创建一个标题(翻译)并将其与折扣相关联。这是我尝试过的:
$discount = new Discount;
/*create a new label*/
$labelKey = Label::max('key') + 1;
$label = new Label(array('key' => $labelKey));
$label->save();
/*create a new title (and associate it with the label)*/
$title = new Translation(
array(
'phrase' => $input['title'],
'languageId' => 3,
'labelId' => $label->id
));
$title->save();
$discount->save();
$discount->titles()->save($title);
显然,$discount->titles()->save($title);
部分不起作用。仅当我手动执行此操作时,标题才会附加到折扣上:$discount->titleLabelId = $label->id
。有没有办法使用 ORM 来做到这一点?
最佳答案
在您的折扣模型中,您的关系是否设置为使用正确的表和外键?
class Discount extends Eloquent
{
public function titles()
{
return $this->belongsTo('Translation', 'translations', 'titleLabelId');
}
}
关于php - Laravel 4 - 外键约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260199/