繁体   English   中英

如何在Laravel 5.3中使用多态关系?

[英]How to use Polymorphic relationship in Laravel 5.3?

我正在使用laravel 5.3,并且有以下情况

我有2个型号

  1. 机器人
  2. 位置

一个机器人可以有多个位置,但是一个位置只能属于一个机器人,并且每当一个机器人拥有一个新位置时,位置表中的计数字段就会增加

我要尝试的是我想与Laravel和Eloquent一起使用多态关系,我想通过使用distinct()在最后一次更新之前获取所有机器人的所有位置?

顺便说一下,位置表中的Locatable_id是指机器人ID。 这是我的模特

机器人型号

public function locations() {
      return $this->morphMany('App\Models\Location', 'locatable');
    }

位置模型

public function locatable() {
      return $this->morphTo();

}

位置表

在此处输入图片说明

任何帮助将非常感激。 谢谢。

这是我的解决方法:)

// Grap all Robots with it's locations and Customer
  $robots = Robot::whereHas('locations', function($query){
    $query->whereNotNull('locatable_id')->orderBy('updated_at');
  })->with('locations')->with('customers')->get();

//Filter only latest Locations for each Robot
  $filterLocations= $robots->map(function($robot){
    $robot->timeEntries = $robot->locations()
      ->orderBy('updated_at', 'DESC')
      ->limit(1)
      ->get();
    return $robot;
  });

感谢您的帮助时间:)谢谢samuele-colombo

下面的查询返回所有机器人,并为每个机器人提供最新的位置。 内部函数可用于过滤locations数据。

Robot::with(['locations' => function($q) {
    $q->latest();
}])->get();


我要尝试的是我想与Laravel和Eloquent一起使用多态关系,我想通过使用distinct()在最后一次更新之前获取所有机器人的所有位置?

这不能完全达到您的目标,但是我认为这是一个不错的起点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM