返回laravel中的所有关系数据

iugsix8n  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(114)

我想使用雄辩模型检索数据,并在下面的json响应中返回它。

user[
     transactions[],
     clients[
            ubications[],
            contactos[],
            plans[],
      ]
]

目前,我正在接收用户,事务和客户端数据,但我无法检索客户端属性中的数据,例如ubications[],contactos[]和plans[]。因此,我需要有关子属性的帮助,因为我已经实现了关系。
以下是我使用的模型

User.php

class User extends Authenticatable
{
    use Notifiable,HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function token(){
        return $this->access_token;
    }
    public function transaction(){
        return $this->hasMany(Transaction::class);
    }
    public function plan(){
        return $this->hasManyThrough(Plan::class,Client::class);
    }
    public function ubication(){
        return $this->hasManyThrough(Ubicacion::class,Client::class);
    }
    public function contacto(){
        return $this->hasManyThrough(Contacto::class,Client::class);
    }
    public function client(){
        return $this->hasMany(Client::class);
    }
}

Client.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $fillable=[
        'nombre',
        'ruc',
        'status',
        'user_id'
    ];

    public function contacto(){
        return $this->hasMany(Contacto::class);
    }
    public function feedback(){
        return $this->hasMany(Feedback::class);
    }
    public function plan(){
        return $this->hasMany(Plan::class);
    }
    public function ubication(){
        return $this->hasMany(Ubicacion::class);
    }
    public function user(){
        return $this->belongsTo(User::class);
    }
}
yeotifhr

yeotifhr1#

您可以使用嵌套数据Eager Loading:Laravel文档Eager Loading

$user = User::find(1)
   ->with('clients', 'clients.contacto', 'clients.ubications', 'clients.plans')
   ->get();
In my case I want all products with a relationship It's work for me 
Product::where('id','>',1)->with('categories')->get();

相关问题