Php 在雄辩的关系中访问父值

Php 在雄辩的关系中访问父值,php,laravel,eloquent,Php,Laravel,Eloquent,在我的控制器中 User::find(1)->with('matches')->get() 在模型中 public function matches() { $userAge = $this->age; // Trying to access something like this return $this->hasMany('App\Others', 'location', 'location') ->selec

在我的控制器中

User::find(1)->with('matches')->get()
在模型中

public function matches()
{
    $userAge = $this->age; // Trying to access something like this

    return $this->hasMany('App\Others', 'location', 'location')
                ->selectRaw('*, ('.$userAge.' = age) as match');
}
如何访问用户的年龄,如
$this->age
?或者这可能吗?我已经试着
var\u dump($this)
看看我能得到什么,但是运气不好

我最初的目标是在内部加入
用户
其他人
表/模型。 我有这样一个问题:

SELECT (a.age = b.age) as match
FROM user a 
LEFT JOIN others b ON a.location= b.location 
WHERE a.location = 'Somewhere' 
我知道我可以用Query builder轻松地完成这项工作,但我认为如果我可以使用雄辩的/关系来完成这项工作会更好

希望你们明白我的意思


我对Laravel还是新手。

你可以在有说服力的模型上使用访问器和变异器

public function getAgeAttribute () {
    // add custom query logic here
    ...
    return $queryResult->age;
}
然后,您的用户模型可以作为实例访问其
age
属性:

$user->age
或者在模型本身内:

$this->age


只要在模型上命名一个函数,以
get
开始,以
Attribute
结束,您就可以创建一个mutator,它允许定义自定义属性或修改从现有属性返回的内容。

您弄错了。这种关系应该是这样的:

public function matches()
{
    return $this->hasMany('App\Others', 'location', 'location');
}
然后获取与以下项相关匹配的用户:

$user = User::with('matches')->find(1);
然后您可以访问用户的年龄和匹配项:

User is {{ $user->age }} years old
@foreach ($user->matches as $match)
    {{ $match->id }}
@endforeach

不,我有更多的理由把它放在选择字段中,我不需要只打印它们。我确实需要访问匹配项中的
age
,因为我需要它包含在我的查询中,因为您将此
('.$userAge.=age)视为匹配项。。因为我稍后将使用它来排序和限制结果,比如
orderbymatch DESC limit 10
当我在
matches
这样的“关系”方法中使用它时,这不起作用,我使用
with('matches')
。这只适用于像
User::find(1)->findMyAge()
accessor这样的方法,它绝对适用于“关系”方法,相当于访问常规模型属性。你使用它有什么问题?出现了一个特殊的异常情况?我试图在
匹配项中执行
var\u dump($this->age)
,它是
NULL
。在您提供的访问器代码中,我得到了
ErrorException未定义变量:queryResult
,正如预期的那样。
$queryResult
是一个用于演示的合成变量。你需要把你的真实代码放在这个函数中,然后返回年龄值。是的,我想是这样的。但如果这真的是你的意思,那就没什么新鲜事了。我仍然需要再次手动查找特定的
用户。这只会使我的代码更长,但结果相同。但是谢谢你的努力。