通过Eloquent在laravel中找到两个具有相同值的列?

时间:2022-07-30 07:59:36

I am working on a project where I have a table market which has a buyer_id column and a seller_id column. When a seller puts something on the market, the seller_id and buyer_id are the same which means that the product is for sale right now. After the sale, the buyer_id changes to whoever bought the product.

我正在开发一个项目,我有一个包含buyer_id列和seller_id列的表市场。当卖家在市场上放置东西时,seller_id和buyer_id是相同的,这意味着该产品现在正在出售。销售后,buyer_id会更改为购买产品的人。

Now the place in my application where I am showing all the products up for sale I am doing this query via Eloquent:

现在我在我的应用程序中显示所有待售产品的地方我通过Eloquent进行此查询:

$market_records = Market::where('seller_id', '!=', Auth::user()->id)->where('seller_id', '=', 'buyer_id')->get();

I want only the products up for sale which are not by the same user who has logged in and I want to have only those products where the seller_id and buyer_id is same. Now the problem in the second where statement is that the that it is comparing the seller_id to the string 'buyer_id' which is not what I want. What is way with which I can only fetch the records where the buyer_id is equal to the seller_id.

我只想要出售的产品不是由已登录的同一用户而且我想只有sell_id和buyer_id相同的那些产品。现在第二个where语句中的问题是它将seller_id与字符串'buyer_id'进行比较,这不是我想要的。我只能获取buyer_id等于seller_id的记录的方式是什么。

3 个解决方案

#1


15  

You need to use whereRaw to do it:

你需要使用whereRaw来做到这一点:

$market_records = Market::where('seller_id', '!=', Auth::user()->id)->whereRaw('seller_id = buyer_id')->get();

#2


3  

Option 1: ->whereRaw('column1 = column2')

选项1: - > whereRaw('column1 = column2')

Option 2: When on sale buyer_id == null != seller_id, ->where('buyer_id', '=', null)

选项2:开始销售时buyer_id == null!= seller_id, - > where('buyer_id','=',null)

#3


3  

In recent Laravel versions you can use whereColumn (docs):

在最近的Laravel版本中,您可以使用whereColumn(docs):

$same = Market::whereColumn('seller_id', 'buyer_id')->get();

#1


15  

You need to use whereRaw to do it:

你需要使用whereRaw来做到这一点:

$market_records = Market::where('seller_id', '!=', Auth::user()->id)->whereRaw('seller_id = buyer_id')->get();

#2


3  

Option 1: ->whereRaw('column1 = column2')

选项1: - > whereRaw('column1 = column2')

Option 2: When on sale buyer_id == null != seller_id, ->where('buyer_id', '=', null)

选项2:开始销售时buyer_id == null!= seller_id, - > where('buyer_id','=',null)

#3


3  

In recent Laravel versions you can use whereColumn (docs):

在最近的Laravel版本中,您可以使用whereColumn(docs):

$same = Market::whereColumn('seller_id', 'buyer_id')->get();