Laravel eloquent 从 sql 的数组中查找
Laravel eloquent find in array from sql
我正在使用 Laravel 4.2 开发网站。我有两个 table:articles 和 tags。
这是我的标签table:
id | article_ids | xxxx
2 | 2,41,23,6 | xxxx
我正在使用 Eloquent,我想在 article_ids 列中找到一个特定的 ID。
我怎样才能做到这一点?
我可以像这样在 MySQL 中搜索吗?
感谢您的帮助。抱歉我的英语不好。
正如您刚刚发现的那样,这是一种将标签与文章相关联的非常糟糕的方法,因为它不容易查询。相反,对于两者之间的多对多关系,您需要一个包含列 article_id
和 tag_id
的中间 table。对于具有四个标签的文章,将有四个记录,每个关联一个。
几乎所有的事情都已经说过了——糟糕的设计,你应该避免它等等。没错,我同意。
做正确的事。但是,MySQL 中的操作方式如下:
// say you want tags related to articles 2 and 23
SELECT * FROM tags
WHERE FIND_IN_SET('2', article_ids)
AND FIND_IN_SET('23', article_ids);
// Eloquent
Tag::whereRaw(
'find_in_set(?, article_ids) and find_in_set(?, article_ids)',
[$id1, $id2] // bindings array
)->get();
我正在使用 Laravel 4.2 开发网站。我有两个 table:articles 和 tags。
这是我的标签table:
id | article_ids | xxxx
2 | 2,41,23,6 | xxxx
我正在使用 Eloquent,我想在 article_ids 列中找到一个特定的 ID。 我怎样才能做到这一点?
我可以像这样在 MySQL 中搜索吗?
感谢您的帮助。抱歉我的英语不好。
正如您刚刚发现的那样,这是一种将标签与文章相关联的非常糟糕的方法,因为它不容易查询。相反,对于两者之间的多对多关系,您需要一个包含列 article_id
和 tag_id
的中间 table。对于具有四个标签的文章,将有四个记录,每个关联一个。
几乎所有的事情都已经说过了——糟糕的设计,你应该避免它等等。没错,我同意。
做正确的事。但是,MySQL 中的操作方式如下:
// say you want tags related to articles 2 and 23
SELECT * FROM tags
WHERE FIND_IN_SET('2', article_ids)
AND FIND_IN_SET('23', article_ids);
// Eloquent
Tag::whereRaw(
'find_in_set(?, article_ids) and find_in_set(?, article_ids)',
[$id1, $id2] // bindings array
)->get();