简体   繁体   English

对 Eloquent 的 SQL 查询

[英]SQL query to Eloquent

to implement a basic relationship system I followed this model suggested from a website:为了实现一个基本的关系系统,我遵循了一个网站建议的模型:

user_relationship:
------------------
- user_1
- user_2
- status
- user_action

Where user_1 , user_2 , user_action are foreign keys that references users.id and user_1 < user_2 to avoid duplicate tuples.其中user_1user_2user_action是引用users.iduser_1 < user_2以避免重复元组的外键。

However I'm finding it difficult to write this SQL query in Eloquent (Laravel 5.5):但是我发现很难在 Eloquent (Laravel 5.5) 中编写这个 SQL 查询:

SELECT user_1, user_2
FROM user_relationships
WHERE (user_1 = :user OR user_2 = :user) AND status = 'friends'

This query should return all the tuples where user is either user_1 or user_2 .此查询应返回 user 为user_1user_2所有元组。

I have a very basic knowledge of Eloquent so I'm having a hard time making this work, but since I've seen many people saying that it's better to use Eloquent whenever possible I'd like to use it.我对 Eloquent 有非常基本的了解,所以我很难完成这项工作,但是因为我看到很多人说最好尽可能使用 Eloquent,所以我想使用它。

You do in wrong way.你做错了。 Better solution is to use relations in model.更好的解决方案是在模型中使用关系。 You can make relations such as:您可以建立如下关系:

  • One To One一对一
  • One To Many一对多
  • Many To Many多对多
  • Has Many Through有很多通过
  • Polymorphic Relations多态关系
  • Many To Many Polymorphic Relations多对多多态关系

This will save your time, read it: https://laravel.com/docs/5.5/eloquent-relationships这将节省您的时间,请阅读: https : //laravel.com/docs/5.5/eloquent-relationships

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM