我使用Laravel 5的belongsToMany方法使用中间数据透视表定义相关表.我的应用程序是使用雄辩的模型Tour和TourCategory.在旅游模型中,我有:
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的方法检索巡视表中的所有数据以及相关的类别数据:
$tours = Tour::with('cats')->get();
一切正常.问题是我不希望以当前原始形式的类别数据,我需要首先重新排列它.但是我不能在不首先取消它的情况下覆盖cat属性:
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.6,你可以在unsetRelation之前取消关系
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。