kjdion84
kjdion84

Reputation: 10044

Laravel relationship with single column

I have a table called "fields":

Schema::create('fields', function (Blueprint $table) {
    $table->increments('id');
    $table->string("label");
    $table->string("name")->unique();
    $table->text("options")->nullable();
    $table->timestamps();
});

I want to have another table which simply stores the ids of some of the fields. I will call this default_fields.

I basically want a relationship or logic that allows me to grab these default_fields like I would with any other relation:

Schema::create('default_fields', function (Blueprint $table) {
    $table->increments('id');
    $table->integer("field_id");
});

How can I create a relationship that grabs all the fields whose id's are present in this table? I also want to be able to sync().

Would I just make a model for DefaultField and then do something like Field::whereIn('id', DefaultField::get()->pluck('id'))?

And then code my own sync() logic? Is there a super easy way to do this that I'm missing? I'd also like to be able to sort this like I would any other relation.

Upvotes: 0

Views: 72

Answers (2)

Prince Lionel N'zi
Prince Lionel N'zi

Reputation: 2588

You can have a model Field that has this relationship:

public function defaultFields()
{
    return $this->hasMany('App\DefaultField');
}

In you controller, you can fetch the Field with his related DefaultFields like:

$fields = Field::with('defaultFields')->get();

You can have a similar method field in your DefaultField model:

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

In you controller, you can fetch the DefaultField with his parent Field:

$defaultFields = DefaultField::with('field')->get();

Upvotes: 1

Nikita
Nikita

Reputation: 408

In your case, more productive will be 'is_default' boolean property in the fields table.

Upvotes: 0

Related Questions