簡體   English   中英

用這個表結構將結構模型化到 Laravel 中?

[英]Model structure into Laravel with this table structure?

我正在將舊的普通 PHP RESTful API 項目遷移到 Lumen API 項目中。 我被困在 Eloquent 模型的結構上,負責從數據庫中獲取、插入、更新或刪除數據。 我想知道模型的結構和映射。

下面是一些表結構:

stop {id, stop_name, stop_code, stop_status}

stop_detail {detail_id, stop_id, description, created_on, modified_on}

image {image_id, image_path, description, seq_order, is_thumb}

image_stop_mapping {stop_id, image_id, order}

place {place_id, place_title, description, place_status, order}

image_place_mapping {place_id, image_id, order}

現在,當我訪問停止模型時,我希望能夠在單個模型訪問中訪問 stop_detail、stop_images、stop_places、place_images。 它應該像

public function findByStopId($stopId) {
    return Stop::where('id', $stopId)->with('stop_detail', 'stop_detail.stop_images', 'places', 'places.images')->get();
}

誰能幫我創建更好的 Eloquent 模型結構?

因此,例如在您的停止模型中,您可能有以下內容,但我不確定實際關系,所以請耐心等待。

  class Stop extends Model {

      public function stopdetails(){
          return $this->hasMany(StopDetails::class, 'stop_id');
     }

 }

然后稱之為:

 public function findByStopId($stopId) {
       return Stop::where('id', $stopId)->with('stopdetails')->get();
 }

不知道總結構等,但希望它可以幫助您找到或至少給您一個入門

您想使用“熱切加載”( https://laravel.com/docs/5.1/eloquent-relationships#eager-loading ),對嗎?

所以你寫的方法非常好 - 如果應用程序知道這些關系。

基本上你可以很好地猜到它們(因為編寫它的人使用了一個簡單的命名約定。)

舉個例子: image_stop_mapping {stop_id, image_id, order}stop_detail {id, stop_id, description, created_on, modified_on}

class Image extends Model 
{
   // ...
}

class ImageStopMapping extends Model
{
  public function image()
  {
    return $this->belongsTo('App\Image');
  }

  public function stop()
  {
    return $this->belongsTo('App\Stop');
  }
}

class Stop extends Model 
{
  public function stop_images()
  {
    return $this->hasManyThrough('App\Image', 'App\ImageStopMapping');
  }

  public function details()
  {
    return $this->hasMany('App\StopDetail');
  }
}

class StopDetail extends Model 
{
  public function stop()
  {
    return $this->belongsTo('App\Stop');
  }
}

沒有測試它,但這應該朝着正確的方向發展。

暫無
暫無

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

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