[英]Correct way to define many to many relationship with Laravel
我有兩個型號:
BlogPost模型:
class BlogPost extends Model {
protected $table = 'blog_posts';
public function categories()
{
return $this->belongsToMany( 'BlogCategory', 'blog_category_post', 'post_id', 'category_id' );
}
}
和BlogCategory模型:
class BlogCategory extends Model {
protected $table = 'blog_categories';
public function posts()
{
return $this->belongsToMany( 'BlogPost', 'blog_category_post', 'category_id', 'post_id' );
}
}
對於2個模型,在belongsToMany()中使用第3個和第4個參數是否正確?
它似乎正在工作,因為在調用attach()方法時填充了數據透視表:
if ( is_array( $request->get('categories') ) && count( $request->get('categories') ) ) {
$post->categories()->attach( $request->get('categories') );
}
但是在使用detach()時出現此錯誤:
調用未定義的方法Illuminate \\ Database \\ Eloquent \\ Collection :: detach()
foreach ( $post->categories as $category ) {
$post->categories->detach( $category->id );
echo "<br />" . $category->id;
}
您在關系實例上有調用detach
,而不是集合。
foreach ($post->categories as $category) {
$post->categories()->detach($category->id);
// ^^
}
順便說一句,似乎你想要刪除所有類別。 您可以通過簡單地不將任何內容傳遞給detach
方法來實現:
$post->categories()->detach();
效率更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.