【发布时间】:2018-11-07 03:15:59
【问题描述】:
我通过第三个表在 2 个表之间建立关系。我总共有 3 张桌子。
1.) 地址
Schema::create('addresses', function (Blueprint $table) {
$table->increments('id');
$table->text('line_1_number_building')->nullable();
$table->text('line_2_number_street')->nullable();
$table->text('line_3_area_locality')->nullable();
$table->text('city')->nullable();
$table->text('zip_code')->nullable();
$table->text('state_province_county')->nullable();
$table->text('country')->nullable();
$table->longText('other_address_details')->nullable();
$table->timestamps();
});
2.) 员工
Schema::create('staffs', function (Blueprint $table) {
$table->increments('id');
$table->integer('staff_category_id');
$table->integer('gender_id');
$table->text('staff_job_title')->nullable();
$table->text('staff_first_name')->nullable();
$table->text('staff_middle_name')->nullable();
$table->text('staff_last_name')->nullable();
$table->text('staff_qualifications')->nullable();
$table->date('staff_birth_date');
$table->longText('other_staff_details')->nullable();
$table->timestamps();
});
3.) 员工地址
Schema::create('staff_addresses', function (Blueprint $table) {
$table->increments('id');
$table->integer('staff_id');
$table->integer('address_id');
$table->date('date_address_from')->nullable();
$table->date('date_address_to')->nullable();
$table->timestamps();
});
现在我想获取任何员工条目的所有地址列表。我尝试了下面的代码,但它返回的地址与员工 ID 的 ID 匹配
我尝试了什么
public function saddresses()
{
return $this->hasManyThrough('App\addresses','App\staff_addresses','staff_id','id');
}
我得到了什么
Address : [{"id":3,"line_1_number_building":"Hasan 2 line 1","line_2_number_street":"Hasan 2 line 2","line_3_area_locality":"Hasan 2 line 3","city":"Hasan 2 city","zip_code":"Hasan 2 zip code","state_province_county":"Hasan 2 state","country":"Hasan 2 country","other_address_details":"Hasan 2 other details","created_at":null,"updated_at":null,"staff_id":5},{"id":4,"line_1_number_building":"Sadiq 2 line 1","line_2_number_street":"Sadiq 2 line 2","line_3_area_locality":"Sadiq 2 line 3","city":"Sadiq 2 city","zip_code":"Sadiq 2 zip code","state_province_county":"Sadiq 2 state","country":"Sadiq 2 country","other_address_details":"Sadiq 2 other details","created_at":null,"updated_at":null,"staff_id":5}]
你能指导我如何建立适当的关系吗?
问候, 哈桑·拉贾尼。
【问题讨论】:
-
向你展示雄辩的控制器功能
-
从您的表格看来,您可能需要 belongsToMany 关系。
标签: laravel laravel-5.7