Think I'm missing something obvious here, but I want to define a one way, one to one relationship from table_1 to table_2, e.g. table1 schema:
Schema::create('table1', function (Blueprint $table) {
// Some field definitions
$table->integer('table2_id')->unsigned();
$table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
});
Table 2 doesn't know anything about Table 1, so just has a bunch of fields defined. Model for Table 1 has:
public function table2() // Get table2 record
{
return $this->hasOne('App\Table2');
}
Questions:
a.) Is that relationship in the record necessary just to be able to lookup the relevant table2 record from a table1 record?
b.) How do I set the relationship in my code? Currently my controller code is:
$table_1_record = new Table1();
// What code here to define the relationship, using Eloquent? Or do I just do:
$table_1_record->table2_id = my_table2_record->id;
// But this just sets it manually doesn't it, rather than using Eloquent?
Thing that is confusing me is in here: https://laravel.com/docs/5.6/eloquent-relationships#one-to-one a bit further down from the link, where it says
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key.
Applying that example to my code, the thing is I don't want to have to define a table1_id in my Table_2 - but sounds from that quote from the docs that I need to, to find a table2 record from table1...?
c.) Is there any point in this line in the migration: $table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
and indeed using Eloquent at all (I want to do things the proper Laravel way), or shall I just simply manually set table2_id as in question b.) above?
Note: I don't want to define the inverse of the relationship, as I don't need to find a table_1 record from a table_2 record.
Thanks for any help.