How to use Polymorphic relationship in Laravel 5.3?
我正在使用laravel 5.3,并且有以下情况
我有2个型号
一个机器人可以有多个位置,但是一个位置只能属于一个机器人,并且每当一个机器人具有一个新位置时,位置表中的计数字段就会增加
我要使用的是Laravel和Eloquent的多态关系,我想通过使用distinge()来最后更新所有机器人的所有位置?
顺便说一句,位置表中的Locatable_id是指机器人ID。这是我的模特
机器人模型
1 2 3 | public function locations() { return $this->morphMany('App\\Models\\Location', 'locatable'); } |
位置模型
1 2 | public function locatable() { return $this->morphTo(); |
} ??
位置表
任何帮助将不胜感激。谢谢。
这是我的解决方法:)
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 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
下面的查询返回所有机器人,并为每个机器人提供最新的位置。内部函数可用于过滤
1 2 3 | Robot::with(['locations' => function($q) { $q->latest(); }])->get(); |
what I am trying to is that I want to use polymorph relation with
Laravel and Eloquent, I want to get all the Locations of all Robots by
last updated by using distinct() ?
这不能完全达到您的目标,但我认为这是一个不错的起点。