【问题标题】:Laravel 4.2 get data from main with only pivot data?Laravel 4.2 仅从主数据获取数据?
【发布时间】:2015-08-18 07:36:31
【问题描述】:

我有一个名为 emails 的表,它有一个数据透视表,在该数据透视表中有一个名为“hash”的列。是否也可以通过电子邮件发送该哈希也属于?

我试过了,

$email = Email::with(array('projects' => function($query) use($id) {
    $query->where('hash', '=', $id); 
}))->get(); 

但这会返回电子邮件表中的所有行,而不仅仅是与哈希匹配的行。有没有办法搜索数据透视表并从电子邮件表中取回相关的行?

【问题讨论】:

  • 听起来你想要 wherePivot() 函数。

标签: php mysql laravel eloquent relational-database


【解决方案1】:

当您在Email 类中定义projects 方法时,您可以使用withPivot 方法将透视列添加到模型中:

public function projects()
{
    return $this->belongsToMany('Project')->withPivot('hash');
}

然后您可以通过以下方式使用它:

$email = Email::with(['projects' => /* ... */])->get();

foreach ($email as $item) {
    echo $item->title; // regular field on `email`
    echo $item->pivot->hash; // field on the pivot table
}

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 2015-12-17
    • 2017-10-19
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2015-06-02
    • 2015-12-25
    • 2022-01-20
    相关资源
    最近更新 更多