问题
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.
Now the place in my application where I am showing all the products up for sale I am doing this query via 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
.
回答1:
You need to use whereRaw
to do it:
$market_records = Market::where('seller_id', '!=', Auth::user()->id)
->whereRaw('seller_id = buyer_id')->get();
Anyone looking for this solution keep in mind since Laravel 5.2 it's possible to use whereColumn
method instead, so above code in Laravel 5.2 and up could look like this:
$market_records = Market::where('seller_id', '!=', Auth::user()->id)
->whereColumn('seller_id', 'buyer_id')->get();
You can find details in this commit
回答2:
In recent Laravel versions you can use whereColumn
(docs):
$same = Market::whereColumn('seller_id', 'buyer_id')->get();
回答3:
Option 1: ->whereRaw('column1 = column2')
Option 2: When on sale buyer_id == null != seller_id, ->where('buyer_id', '=', null)
来源:https://stackoverflow.com/questions/27290101/find-two-column-in-laravel-which-have-equal-values-via-eloquent