$distance = DB::select(
DB::raw("
SELECT a.distance
FROM ( SELECT user_id, street, store_name,
(
'".$mean_radius_of_Earth."' *
acos(cos(radians('".$latitude."')) *
cos(radians(latitude)) *
cos(radians(longitude) -
radians('".$longitude."')) +
sin(radians('".$latitude."')) *
sin(radians(latitude)))
) AS distance
FROM addresses ) AS a
WHERE id= '". $address_id."'
")
);
我必须使用此address_id来获取特定行的所有列,这是主键,但我收到错误: - 找不到列:1054'where子句'中的未知列'id'但是当我尝试使用user_id实现这一点然后我得到所有字段数据,user_id(不是primary_key)你的帮助将不胜感激, 提前致谢并抱歉不合适的英语
答案 0 :(得分:0)
您不在子请求中选择ID,或者您在子查询中进行选择,或者在子选择中选择字段ID:
$distance = DB::select(
DB::raw("
SELECT a.distance
FROM ( SELECT user_id, street, store_name,
(
'".$mean_radius_of_Earth."' *
acos(cos(radians('".$latitude."')) *
cos(radians(latitude)) *
cos(radians(longitude) -
radians('".$longitude."')) +
sin(radians('".$latitude."')) *
sin(radians(latitude)))
) AS distance
FROM addresses
WHERE id= '". $address_id."') AS a
")
);
答案 1 :(得分:0)
在这种情况下,我会利用Eloquent's Appends功能的强大功能。
在您的情况下,它可能看起来像以下一样,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['distance'];
/**
* Get the distance for the user.
*
* @return int
*/
public function getDistanceAttribute()
{
$distance = // Crazy math for distance insert here
// To get address long and lat stored in separate database
// I would eager load them in the query call and then in this
// function you'd already have the values ready to go in memory
$distance = $this->address->long...
return $distance;
}
}
这个解决方案的优点是你可以利用Eloquent的查询,防止SQL注入混乱,并保持与你的模型绑定而不是查询。
use App\User;
foreach(User::all() as $user) {
echo $user->distance; // Print's out the distance you wanted
}
echo User::where('id', '=', $address_id)->first()->distance; // Prints out specific user's distance.