我正在使用Laravel 5的belongsToMany
方法来定义使用中间枢表关联的相关表。我的应用程序正在使用eloquent模型Tour和TourCategory。在Tour Model中,我有:
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
方法检索来自tour表的所有数据以及相关联的类别数据:
$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);
}
有人能解释一下这背后的逻辑吗?
foreach
方法工作方式的一个特性。我记不清了,但我可能只是按照上面的代码先使用了unset。 - Inigo