0

我的问题只是如何将数据插入连接表(user_book)而不在主表(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

但问题是当我插入 Books 表中存在的新书(例如 Mike,如 B3)时。副本将出现在 books 表中,上表如下:

  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

现在我要解决的问题有意义吗?或者也许我根本没有唯一的书籍清单?

如果我要插入鉴于数据库用户和书籍用户<--->书籍与 users_books 相关,我们需要确保当我们将书籍记录插入数据库时​​它不是重复的。此外,如果书存在,则将插入关系而不是书记录。怎么可能做到这一点?一种方法是说

$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 然后检查关系,看看用户和书籍之间是否存在关系,如果存在则不要插入它。此外,我是否需要更改 mysql db 结构中的任何内容以避免这种情况。

上面的代码不起作用,但应该让我知道我在说什么。

更新:

总之,如果两个用户喜欢同一本书,我只想在连接表 (users_books) 中插入一条记录(book),而不是在表中创建新记录。使用唯一 sql 标记不起作用,因为它保留唯一列表,但它阻止将多个关系插入连接表 users_books。

4

1 回答 1

1

你可以这样做:

$b = new book();  
$b->where('id_book', $data['user_booklist'][$i]['id'])->get();
// I believe you can do this as well, but I'm not sure:
// $b->where('id', $data['user_booklist'][$i]['id'])->get();

$u = new user();
$u -> where('id_user', $data['user_profile']['id'])-> get();

if( $b->exists() && $u->exists() )
{
   // This saves the relationship between the book and the user
   $b->save($u);
}
else  
{
   // Could not find the book or the user
}

您应该查看有关保存关系的数据映射器手册

于 2012-05-02T09:37:07.750 回答