laravel雄辩的更新有许多ID数组
我需要更新hasmany与一组id的关系 常见问题解答模型。laravel雄辩的更新有许多ID数组,laravel,eloquent,Laravel,Eloquent,我需要更新hasmany与一组id的关系 常见问题解答模型。 class Faq extends Model { public function products(){ return $this->belongsToMany(Product::class, 'faq_products'); } } 我有很多关系的产品模型和数据透视表“faq_products” 常见问题解答产品表 Schema::create('faq_products', funct
class Faq extends Model
{
public function products(){
return $this->belongsToMany(Product::class, 'faq_products');
}
}
我有很多关系的产品模型和数据透视表“faq_products”
常见问题解答产品表
Schema::create('faq_products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('faq_id')->unsigned()->nullable();
$table->foreign('faq_id')->references('id')->on('faqs')->onDelete('cascade');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamps();
});
我从与faq相关的请求中获得了一系列产品ID,但不确定如何更新关系
排列
我敢打赌,这是你想要的:
class FaqController extends Controller
{
public function update(Request $request)
{
$faq = Faq::findOrFail($request->input('faq_id');
//attached products [4,5,6]
$faq->products()->attach($request->input('product_ids')); // [4, 3, 2];
//attached products [2,3,4,5,6]
}
}
如果您以前连接过其他产品(示例id=4、5和6),并且希望在连接4、3和2时删除它们;使用而不是附加
//attached products [4,5,6]
$faq->products()->sync($request->input('product_ids')); // product_ids = [4,3,2]
//attached products [4,3,2]
@vimuth对数据使用
input()
方法,对异常使用findOrFail()
方法(如果id不存在),它将返回一个非常好的答案,没有足够的单词来感谢…@N69S显著改进了答案。
//attached products [4,5,6]
$faq->products()->sync($request->input('product_ids')); // product_ids = [4,3,2]
//attached products [4,3,2]