php - Laravel 4 - 外键约束失败

标签 php mysql orm laravel

我有以下关系:

折扣:

<?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/

相关文章:

php - cURL SSL PUT/POST (php) 的延迟响应(NSS 与 OpenSSL)

php - 新图像已创建,但旧图像显示 JS(AJAX)

php - 在 PHP 中执行依赖于变量的 SQL 查询

MySQL:过程参数问题

java - JDBC 和 Hibernate 之间的中间地带?

c# - Entity Framework - 通过更改外键更新关系

php - 有没有办法访问包含 php 函数的 HTML 元素类名?

mysql - 嵌套 SELECT,还是我太复杂了?

symfony - 从现有数据库创建实体

php - 如何在分类页面获取多个分类帖子?