vendredi 1 juillet 2016

Relationships and querying related models

I am trying to work out if I have done something correctly. I have a Department Model. A Department can have many DepartmentObjectives. I have also set up the inverse. So this relationship is fine.

I then have a User Model. A User can have many User Objectives, this is set up fine. In my user_objectives table however, there is a link to a department Objective

$table->integer('department_objectives_id')->unsigned()->default(0);
$table->foreign('department_objectives_id')->references('id')->on('department_objectives')->onDelete('cascade');

So a user objective is linked to a department objective. Is this something I need to specify within my models? So should my UserObjectives model have

class UserObjectives extends Model
{
    use SoftDeletes;

    protected $table = 'user_objectives';
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function departmentObjectives()
    {
        return $this->belongsTo('App\DepartmentObjectives');
    }
}

For some reason it seems a bit strange doing this. Anyways, when I create a user objective currently, a department objective is selected and I store the id to the department objective. So within my view I can do something like this



And that will display the id of the department objective it is related too. How can I get the name of the department objective?

Any adivce appreciated

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire