在laravel 5中访问嵌套关系

时间:2019-04-11 08:01:44

标签: laravel laravel-5 eloquent relation

我有以下3种型号:

Date
Property
PropertyDetail

这是我按顺序写的表的迁移 日期:

 public function up()
{
    Schema::create('dates', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->dateTime('date');
        $table->timestamps();
    });
}

属性:

 public function up()
{
    Schema::create('properties', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('type');
        $table->text('title');
        $table->integer('base_capacity');
        $table->timestamps();
    });

和PropertyDetail:

 public function up()
{
    Schema::create('property_details', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('property_id');
        $table->string('state');
        $table->string('city');
        $table->timestamps();
    });
}

我试图从迁移中删除不必要的字段,以便保持干净,所以这是我的两个联系日期和财产 日期模型:

 public function properties() {
    return $this->belongsToMany(Property::class);
 }

和属性模型:

 public function dates(){
    return $this->belongsToMany(Date::class);
}
 public function features(){
    return $this->hasMany(Feature::class);
}

好,现在终于在我的控制器中,我想这样做:

 $search = Date::with('properties')
        ->where('date',$someday)->get()


     ->and some how here i want to select the city from the property detail table
;

所以这是我的问题,现在我可以轻松访问属性并显示其名称,但是从该关系中,我应该如何访问要素关系并从中选择城市(如果我要使用联接或某些东西的话),我希望我已经足够清楚了我想做什么

1 个答案:

答案 0 :(得分:1)

您可以这样做:

属性模型:

public function details(){
    return $this->belongsToMany(Details::class,'property_details','id','property_id');
}

日期模型:

 public function properties() {
     return $this->belongsToMany(Property::class);
 }

 public function propertiesDetails() {
     return $this->properties()->with('details');
 }

,并且在您的控制器中,您可以通过使用以下属性来获取属性的详细信息:

 $search = Date::with('propertiesDetails')
    ->where('date',$someday)->get();

现在您可以访问属性的详细信息。

希望有帮助。