【问题标题】:Model structure into Laravel with this table structure?使用此表结构将模型结构转换为 Laravel?
【发布时间】:2016-11-12 13:35:39
【问题描述】:

我正在将旧的普通 PHP RESTful API 项目迁移到 Lumen API 项目中。我被困在 Eloquent 模型的结构上,负责从数据库中获取、插入、更新或删除数据。我想知道Model的结构和映射关系。

这是一些表结构:

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 模型结构?

【问题讨论】:

  • 您需要更多地研究模型关系等,例如 hasMany、hasOne、manyToMany 等
  • 查看 laravel.com/docs/master/eloquent-relationships 以正确定义 Stop 模型中的关系,然后您将能够使用 with()/load() 方法正确加载它们
  • 其中一个答案对您有帮助吗?

标签: php mysql laravel lumen


【解决方案1】:

因此,例如在您的停止模型中,您可能会有以下内容,但我不确定实际的关系,所以请耐心等待。

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

不知道整体结构等,但希望它可以帮助您找到或至少给您一个入门

【讨论】:

    【解决方案2】:

    你想使用“急切加载”(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');
      }
    }
    

    没有测试,但这应该是正确的方向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2011-06-10
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多