从与数据透视表关联的表中获取数据

时间:2020-04-13 10:34:27

标签: laravel

我有很多关系,中间有一张桌子

用户

报价

user_quote(这是中间语言)

在此中间表中,我与另一个表(quotes_time)之间存在一对多关系

图像数据库架构

ER DIAGRAM

用户模型:

    public function quotes()
 {
    return $this->belongsToMany(Quote::class, 'quote_user');
 }

报价模型:

public function users()
{
  return $this->belongsToMany(User::class, 'quote_user');
}

如何从quotes_time表中获取数据?

在用户控制器中,我有这个:

 $users = User::with('latestQuotes','latestQuotes.vehicle')->filter($request);

我真正需要的是从用户那里获取quotes_time数据

对不起,我的英语水平

1 个答案:

答案 0 :(得分:0)

您有2个选择。

1。从数据透视模型访问BelongsTo关系。

用户模型:

public function quotes()
{
    return $this->belongsToMany(Quote::class, 'quote_user')->using(QuoteUser::class);
}

报价模型:

public function users()
{
    return $this->belongsToMany(User::class, 'quote_user')->using(QuoteUser::class);
}

QuoteUser数据透视模型

class QuoteUser extends Pivot
{
    public function time()
    {
        return $this->belongsTo(QuoteTime::class, 'user_quotes_id');
    }
}
$users = User::with('quotes')->get();

foreach ($user->quotes as $quote) {
    $quote->pivot->time->start;
}

2。在用户和QuoteTime(或Quote和QuoteTime)之间使用hasManyThrough关系

用户模型:

public function quotes()
{
    return $this->belongsToMany(Quote::class, 'quote_user')->using(QuoteUser::class);
}

public function quoteTimes()
{
    return $this->hasManyThrough(QuoteTime::class, QuoteUser::class);
}

报价模型:

public function users()
{
    return $this->belongsToMany(User::class, 'quote_user')->using(QuoteUser::class);
}

public function quoteTimes()
{
    return $this->hasManyThrough(QuoteTime::class, QuoteUser::class);
}
$users = User::with('quoteTimes')->get();

foreach ($user->quotes_times as $quote_time) {
    $quote_time->start;
}
// or
$user = User::with('quotes.quoteTimes')->get();

foreach ($user->quotes as $quote) {
    $quote->quote_times->...
}