雄辩的一对多对多

时间:2018-04-19 19:30:45

标签: laravel-5 laravel-eloquent

大家好,我从Laravel开始,口若悬河,我已经遇到了问题。

我有用户,每个用户可以有多辆车,一辆车可以有多个租赁。我想列出属于当前用户的每辆车的所有租金。

用户模型:

class User extends Authenticatable
{
    use Notifiable;

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

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


    public function vehicule()
    {
        return $this->hasMany('App\Models\Vehicule');
    }

Vehicule模型:

use Illuminate\Database\Eloquent\Model;

class Vehicule extends Model
{
    protected $fillable = [

    'user_id',
    'published',
    'rented'
];


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

public function rental()
{
    return $this->hasMany('App\Models\Rental');
}

租赁模式:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Rental extends Model
{

    protected $fillable = [
        'from_date',
        'to_date',
        'amount_total',
        'vehicule_id'
    ];


    public function vehicule()
    {
        return $this->belongsTo('App\Models\Vehicule');
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用现有的关系:

$rentals = $user->load('vehicule.rental')->pluck('vehicule.rental')->collapse();

或者向User添加HasManyThrough关系:

public function rental()
{
    return $this->hasManyThrough(Rental::class, Vehicule::class);
}

$rentals = $user->rental;