我正在使用 Laravel 5belongsToMany
使用中间数据透视表定义相关表的方法。我的应用程序正在使用雄辩的模型Tour and 旅游类别。在游览模型中我有:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model
{
public function cats(){
return $this->belongsToMany('App\TourCategory', 'tour_cat_assignments', 'tour_id', 'cat_id');
}
}
在我的控制器中,我使用 Laravel 检索游览表中的所有数据以及相关的类别数据with
method:
$tours = Tour::with('cats')->get();
一切都很好。问题是我不想要当前原始形式的类别数据,我需要首先重新排列它。但是我无法覆盖cats
属性而不先取消设置它:
public function serveTourData(){
$tours = Tour::with('sections', 'cats')->get();
foreach($tours as $tour){
unset($tour->cats); // If I unset first, then it respects the new value. Why do I need to do this?
$tour->cats = "SOME NEW VALUE";
}
Log::info($tours);
}
有人可以解释一下这背后的逻辑吗?
要覆盖某些模型上的关系,您可以使用:
public function serveTourData(){
$tours = Tour::with('sections', 'cats')->get();
foreach($tours as $tour){
$tour->setRelation('cats', "SOME NEW VALUE");
}
Log::info($tours);
}
对于 Laravel 5.4 - setRelation https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_setRelation
当然,如果你使用 laravel >= 5.6,你可以通过以下方式取消关系取消设置关系 https://github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php#L715
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)