首页 文章

Laravel 5.2 laravel如何对待这种属于自己的关系?

提问于
浏览
1

我有3个表,其中列出了以下字段:

Pricings

  • id

  • route_id

Routes

  • id

  • from_city_id

  • to_city_id

Cities

  • id

  • 名字

到目前为止,字段的关系是: pricings belong to a routeroutes belongs to city .

但是我不确定这些关系,因为 from_city_idto_city_id 是与 id id 相关的外键 .

也许我错误地设计我的 table 或其他东西 .

route_idRoutes 表上 id 的外键 . from_city_idto_city_idCities 表上 id 的外键 .

我如何定义这3个表的关系,这样我就可以从pricings模型获得 from city nameto city name ,如 $pricing->from_city->name$pricing->to_city->name

任何帮助赞赏 .

UPDATE:

我的定价模型:

public function route()
{
    return $this->belongsTo(Route::class);    
}

我的路线模型:

public function pricing(){
    return $this->hasOne(Pricing::class);    
}

public function zone(){
    return $this->belongsTo(Zone::class);    
}

public function city(){
    return $this->belongsTo(City::class);    
}

public function from_city(){
    return $this->belongsTo(City::class);    
}

public function to_city(){
    return $this->belongsTo(City::class);
}

现在我可以使用 $pricing->route->from_city->name$pricing->route->to_city->name

它显示了正确的结果,但如何使用Laravel实现这一目标?

这是否意味着Laravel将假设 route 表具有字段 to_city_idfrom_city_id ,因为路由模型中的方法是 to_city()from_city()

谢谢

2 回答

  • 2

    一种解决方案可能是进行迁移(新表或更改为现有表) . https://laravel.com/docs/5.3/migrations

    Laravel的架构构建非常方便:https://laravel.com/docs/5.0/schema

    routes 迁移的一个例子是:

    • 进行迁移:

    php artisan make:迁移路线

    • 迁移看起来像:
    
    使用Illuminate \ Database \ Schema \ Blueprint;使用Illuminate \ Database \ Migrations \ Migration;
    
    class CreateUserRole extends Migration {/ ** *运行迁移 .  * * @return void * / public function up(){Schema :: create('routes',function(Blueprint $ table){
    
    ```java
    $table->increments('id');
            $table->foreign('id')->references('route_id')->on('pricings')->onDelete('cascade');
    
            $table->integer('from_city_id')->unsigned()->index();
            $table->foreign('from_city_id')->references('id')->on('cities')->onDelete('no action');             
    
            $table->integer('to_city_id')->unsigned()->index();
            $table->foreign('to_city_id')->references('id')->on('cities')->onDelete('no action');    
    
            $table->timestamps();
    
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('routes');
    }
    

    }

    
    以上由于某种原因将无法在此处正确显示,因此这里是一个清理后的视图链接:[http://viper-7.com/kfgUjt](http://viper-7.com/kfgUjt)
  • 0

    试试这个:

    在定价模型中:

    //if pricing and route have one to one(hasOne) relationship or you may change it to one to many(hasMany)
    
    public function routes(){
        return $this->hasOne('App\Routes','id','route_id'); 
    }
    

    在路线模型中:

    public function from_city(){
       return $this->hasOne('App\Cities','id','from_city_id');
    }
    
    public function to_city(){
           return $this->hasOne('App\Cities','id','to_city_id');
    }
    

相关问题