请教 eloquent collection 中调用 model 方法的正确方式
user表与compony表为多对多关系,通过中间表company_user表关联。
user model中定义blongsToMany
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function belongsToCompanies()
{
return $this->belongsToMany(Company::class)->withTimestamps();
}
}
在user对象中调用没有问题
$companies = User::find(1)->belongsToCompanies()->get()
如果User查询是个集合
$users = User::find([1,2,3]); //Illuminate\Database\Eloquent\Collection
$users->belongsToCompanies()->get();
则提示找不到collection->belongsToCompanies方法,这个也是理解的。(但是搜索到有些讲模型关系的文章就是这样写)
如果遍历的话似乎效率很低,也能不使用with。
请教一下$users中的model集合批量关联查询belongsToCompanies的方式?
eloquent 5.8.24,未使用laravel。
推荐文章: