簡體   English   中英

Laravel 5.2 laravel如何對待這種歸屬關系?

[英]Laravel 5.2 How laravel treat this belongsto relationship?

我有3個表格,下面列出了這些字段:

Pricings

  • ID
  • ROUTE_ID

路線

  • ID
  • from_city_id
  • to_city_id

城市

  • ID
  • 名稱

到目前為止,字段之間的關系是: pricings belong to a route ,而routes belongs to city

但我不知道這些關系,因為from_city_idto_city_id是與外鍵idcities

也許我在設計桌子或其他東西時錯了。

route_idRoutes表上id的外鍵。 from_city_idto_city_id是“ Cities表上id外鍵。

我如何定義這3代表的關系,所以我可以from city name ,並to city name從pricings模型,如$pricing->from_city->name$pricing->to_city->name

任何幫助表示贊賞。

更新:

我的定價模型:

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()

謝謝

一種解決方案可能是進行遷移(新表或更改為現有表)。 https://laravel.com/docs/5.3/migrations

Laravel的模式構建非常方便: https ://laravel.com/docs/5.0/schema

routes遷移的示例為:

  1. 進行遷移:

    php artisan make:遷移路線

  2. 遷移看起來像:

```

使用Illuminate \\ Database \\ Schema \\ Blueprint; 使用Illuminate \\ Database \\ Migrations \\ Migration;

類CreateUserRole擴展了遷移{/ ** *運行遷移。 * * @return void * / public function up(){Schema :: create('routes',function(Blueprint $ table){

        $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

試試這個:

在定價模型中:

//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');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM