【问题标题】:Laravel/Eloquent belongsToMany - Property [people] does not exist on the Eloquent builder instanceLaravel/Eloquent belongsToMany - Eloquent 构建器实例上不存在属性 [人]
【发布时间】:2022-01-15 10:48:55
【问题描述】:

我想找到为雇主申请职位的人,因此我有 manyToMany 关系。

表格..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

后模型

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

控制器

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::where('user_id' , $user_id)->people; // this line

    dd($employees);
}

如果我 $employees = Post::find(//anyNumber//)->people; 效果很好,但对于每个雇主 ID,它必须是动态的。

我试过这个$employees = Post::where('user_id' , $user_id)->people; 但报错

Eloquent 构建器实例上不存在属性 [人]。

【问题讨论】:

  • 你从未执行过你的查询...Post::where('user_id' , $user_id)->first()->people
  • 问题不清楚;大概一个用户有很多帖子。你想为每个人获得关联的people 关系吗?由于您已经有一个用户实例,因此您似乎正在倒退。例如$myPosts = Auth::user()->posts;
  • 一个用户(雇主)​​有很多帖子,很多用户(员工)可以申请这些帖子。重点是雇主应该知道哪些用户申请了每个职位。

标签: php laravel eloquent


【解决方案1】:

我认为你想做的是这样的:

public function index()
{
    $posts = Auth::user()->posts()->with('people')->get();

    return view("index")->with(["posts" => $posts]);
}

这将为您提供所有经过身份验证的用户的帖子并立即加载人员关系,因此在您的 Blade 模板中您可以遍历每个帖子并访问与每个帖子关联的人员:

<ul>
@foreach ($posts as $post)
    <li>{{ $post->name }}</li>
    <li>
        <ul>
    @foreach ($post->people as $person)
            <li>{{ $person->name }}</li>
    @endforeach
        </ul>
    </li>
@endforeach
</ul>

【讨论】:

  • 假设posts 是这里的关系,查询永远不会执行...错过了对get 的调用
  • 谢谢,已修复
  • 我假设 posts() 意味着 Post::all() 并且它仍然在 null 上给出错误 with() ..
  • $myPosts = Post::where('user_id',$user_id)-&gt;get('id'); $employees = Post::find($myPosts)-&gt;people ; 我也尝试传递帖子 ID,这是有道理的,但给出的属性在此集合实例上不存在。
  • 如果 Auth::user()-&gt;posts() 返回 null 说明你没有正确建立关系@fatih-can
【解决方案2】:

find() 返回单个模型。 Post::where('user_id' , $user_id)-&gt;people 仍然是一个 Eloquent Builder 实例。您尚未完成查询并获得模型。使用获取模型的方法(first()find() 等)应该可以解决问题。 像这样:

employees = Post::where('user_id' , $user_id)-&gt;first()-&gt;people;

【讨论】:

  • 哦,谢谢,现在它执行成功了,但我得到的是空数组而不是人员信息.. 我怎样才能正确地得到它
  • @FatihCan 空数组表示没有与给定帖子关联的人
  • 正如我所说,如果我想查看 id = '2' $employees = Post::find(2)-&gt;people; 的职位申请人会给出正确的结果,但查询一个不会:(
  • @FatihCan 您更改后的第一个查询是什么?
  • Post::find(2)Post::where('id', 2)-&gt;first() 的简写;这与您的Post::where('user_id', $user_id)-&gt;first() 不同。注意区别:'id''user_id'。有一个非常明显的可能原因,其中一个会返回结果,而另一个不会。
猜你喜欢
  • 2021-01-06
  • 2020-08-02
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多