代码之家  ›  专栏  ›  技术社区  ›  gileneusz

laravel从多条消息获取用户

  •  1
  • gileneusz  · 技术社区  · 6 年前

    我有 offers id

    Messages 带列的表 offer_id from

    Users 身份证件

    我想让用户从offer开始 $this 在里面 OfferResource 我的目标是让用户至少回复一条信息。

    我开始配置 Offer 使用函数消息获取消息的模型

    public function messages(){
        return $this -> hasMany('App\Message');
    }
    

    所以我可以获取所有消息(从提供资源开始):

    'users' => $this->messages

    我现在应该如何配置消息模型来获取所有用户而不是消息?

    我试着写进去 Message 型号:

    public function fromContact()
    {
        return $this->hasOne(User::class, 'id', 'from');
    }
    

    然后:

    'users' => $this->messages->fromContact

    但我有个错误: "message": "Property [fromContact] does not exist on this collection instance.",

    我应该如何更正我的代码以使其工作?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Adre Astrian    6 年前

    我假设 from 上的字段 Messages 使用用户ID填充表,然后可以建立 belongsToMany 之间的关系 Offer User 模型。因为这实际上是与透视表的多对多关系 messages 是的。

    提供 模型定义

    public function users()
    {
        return $this->belongsToMany('App\User', 'messages', 'offer_id', 'from');
    }
    

    然后从 OfferResource 你可以加载 offers 像这样的数据

    $offers = App\Offer::with('users')->get();

    然后在 $offers 这样地:

    foreach ($offers as $offer) {
        dd($offer->users); // one offer will have multiple users as a Collection
    }
    

    对于 $offer 身份证号码 1 你可以这么做

    $offer = App\Offer::with('users')->find(1)

    然后得到 users 对这个提议发表评论的人 $offer->users

    official documentation 定义多对多关系。

        2
  •  1
  •   Maraboc    6 年前

    在消息模型中,必须指定引用用户的列:

    public function fromContact()
    {
        return $this->hasOne(User::class, 'from');
    }
    

    然后在获取消息循环之后,得到如下用户:

    foreach ($this->messages as $message) {
        $user = $message->fromContact;
        // do somthing with the user :)
    }
    
        3
  •  1
  •   rkj    6 年前

    您的消息表有 from 正在引用的字段 User 模型和 offer_id 引用的字段 Offer 这意味着你有很多关系 提供 用户 是的。

    报价模式

    public function users(){
        return $this->belongsToMany(User::class, 'messages', 'offer_id', 'from')->using('App\Message');
    }
    

    消息透视

    class Message extends Pivot {
         protected $table = 'messages';
    }
    

    用户模型

    public function offers(){
        return $this->belongsToMany(Offer::class, 'messages', 'from', 'offer_id')->using('App\Message');
    }
    

    供给源

    public function toArray($request)
    {
        $users = $this->users; 
    
        return [
            'id' => $this->id,
            ... //add your offer fields here
            'users' => $users->toArray(), // here $users is a laravel Collection
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
    

    从控制器或路由访问

    Route::get('/offer', function () {
        return new OfferResource(Offer::with('users')->find(1)); //eager load users
    });