【问题标题】:Laravel 5: Access attribute from other ModelLaravel 5:来自其他模型的访问属性
【发布时间】:2015-08-11 11:56:22
【问题描述】:

我正在尝试在 whereHas 中使用 whereBetween,但我的 whereBetween 不起作用,因为在 whereHas 内部没有从我的用户模型中获取我的转身属性:

这是我的查询

DB::raw("*, ( 
        3959 * acos( 
        cos(radians(?)) 
        * cos(radians(latitude))
        * cos(radians(longitude) - radians(?)) 
        + sin(radians(?)) 
        * sin(radians(latitude)))
    ) AS distance"))
->having('distance', '<', $distance)
->orderBy("distance")
->setBindings([$lat, $lng, $lat])
->whereHas('user', function($q) {
    $q->whereBetween('date_of_birth',array(Input::get('age_from'),Input::get('age_to')))
      ->where('gender',Input::get('gender'))
      ->where('title','LIKE','%'.Input::get('title').'%');
})
->with('user')
->get();

用户模型

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    public function getDateOfBirthAttribute()
    {
        $ca = \Carbon\Carbon::parse($this->attributes['date_of_birth']);

        return $ca->diffInYears();
    }

}

位置模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Location extends Model {

    protected $table = 'locations';

    public function user()
    {
        return $this->belongsTo('App\User');
    }

} 

查询中的“出生日期”字段未将转换后的值转换为年份,而是以表格中的 YYYY-MM-DD 等日期格式获取值。

【问题讨论】:

  • 那么 DOB 字段是什么样的?
  • 数据库中的 DOB 类型为“日期”,查询中采用日期格式而不是用户模型的年数。所以查询没有发送任何错误,而是将age_from和age_to(数字)与YYYY-DD-MM进行比较。

标签: php eloquent laravel-5


【解决方案1】:

我找到了解决方案,但不需要从其他模型访问属性,只需使用这个 whereBetween。

$q->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,users.date_of_birth,CURDATE())'),array(Input::get('age_from'),Input::get('age_to')));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多