Support the ongoing development of Laravel.io →
Database Eloquent

I have the following relations:

Discount:

<?php
    class Discount extends Eloquent {
        protected $table = 'discount';
        public $timestamps = true;

        public function titles()
        {
            return $this->hasMany('Translation', 'labelId', 'titleLabelId');
        }
    }
?>

Translation:

 <?php
        class Translation extends Eloquent {
            protected $table = 'translations';
            public $timestamps = false;

            protected $fillable = array('phrase');

            public function language()
            {
                return $this->belongsTo('Language', 'languageId');
            }

            public function label()
            {
                return $this->belongsTo('Label', 'labelId');
            }
}
?>

Label:

<?php
    class Label extends Eloquent {
        protected $table = 'label';
        public $timestamps = false;

        protected $fillable = array('key');

        public function translations()
        {
            return $this->hasMany('Translation', 'labelId', 'id');
        }
    }
?>

There are three database tables with the following columns:

Discount:

id | titleLabelId

Translation:

id | languageId | labelId

Label:

id

The problem: I'd like to create a title (translation) and associate it with the discount. Here's what I've tried:

$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']));

$title->language()->associate($language);
$title->label()->associate($label);

$title->save();

$label->translations()->save($title);

$discount->save();

$discount->titles()->save($title);

Apparently, the $discount->titles()->save($title); part doesn't work. The title is only attached to the discount if I do it manually: $discount->titleLabelId = $label->id. Is there a way to do it using the ORM?

Last updated 3 years ago.
0

I'd like to know the same thing.

Last updated 3 years ago.
0

Where is $language being defined? It appears you are missing the languages table and model. If the title is not being saved, then it won't be able to be associated with a discount. Make sure the title is actually being saved in the database in the first part of your code.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.