My Question is simply how to insert data into the join table(user_book) without inserting a duplicate entry into the main table(book).
主要考虑我们的树木表如下:
id Users id Books id Users Books
1 Sam 1 B1 1 1 1
2 Ben 2 B2 2 1 3
3 Mike 3 B3 3 3 3
4 2 2
但是,在我插入一本新书(如Mike等人,B3)时,问题就在于此。 复制件将出现在账簿表上,上表如下:
id Users id Books id Users Books
1 Sam 1 B1 1 1 1
2 Ben 2 B2 2 1 3
3 Mike 3 B3 3 3 4
4 B3 4 2 2
现在,这是否使我试图解决的是什么意思? 或者,我根本不可能有一个独特的书籍清单?
if I am going to insert Given the database users and books users<--->books are related by users_books we need to make sure that when we insert a book record to the db it is not a duplicate. Further, if the book exist, a relation will be inserted and not the book record . How can one do that? One approach is to say
$m=new Book();
$m->where( id_book , $data[ user_booklist ][$i][ id ])->get();
$u = new User();
$u -> where( id_user , $data[ user_profile ][ id ])-> get();
if(!$u->where_related($m))
{
$m -> name = $data[ user_booklist ][$i][ name ];
$m -> id_book = $data[ user_booklist ][$i][ id ];
$m -> save($u);
}
if (book->exist) in the "books" table then check the relation and see if there is a relationship between users and books and if there is then don t insert it. Further do I need to change any thing in the mysql db structure to avoid this.
The above code is not working but should give an idea what I am talking about.
最新情况:
In summary, if two users liked the same book, I just want to insert a record(book) into the join table (users_books) and while not to creating a new record in the table. Using the unique sql tag did not work since it keeps unique list but it prevents from inserting the multiple relationships into the join table users_books.