首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Laravel合并关系

Laravel合并关系
EN

Stack Overflow用户
提问于 2014-06-12 20:11:38
回答 6查看 19.8K关注 0票数 22

有没有办法在laravel中合并两个关系?

这就是它现在的设置方式,但是有没有一种方法可以同时返回合并的两个呢?

代码语言:javascript
复制
  public function CompetitionsHome() {
    return $this->HasMany( 'Competition', 'home_team_id' );
  }
  public function CompetitionsGuest() {
    return $this->HasMany( 'Competition', 'guest_team_id' );
  }
  public function Competitions() {
    // return both CompetitionsHome & CompetitionsGuest
  }
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2014-06-12 20:32:14

尝试使用getter方法获取属性,该方法返回从关系返回的合并集合。

代码语言:javascript
复制
public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}

或者,您可以在返回集合之前调用其他方法以获取不同的结果集。

代码语言:javascript
复制
public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    // `latest()` method is shorthand for `orderBy('created_at', 'desc')`
    // method call.
    $competitionsHome = $this->competitionsHome()->latest()->get();
    $competitionsGuest = $this->competitionsGuest()->latest()->get();

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}
票数 30
EN

Stack Overflow用户

发布于 2016-04-15 17:08:22

如果您更喜欢merge()方法来组合两个集合(关系),它将覆盖具有相同索引键的元素,因此您将丢失从一个关系中获得的一些数据。

您应该选择push()方法,该方法通过将一个集合推送到另一个集合的末尾来创建新的数组键

下面是一个示例:

代码语言:javascript
复制
public function getCompetitionsAttribute($value) {
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // PUSH ONE TO OTHER!
    return $competitionsHome->push($competitionsGuest);
}
票数 8
EN

Stack Overflow用户

发布于 2019-09-18 06:08:26

我已经创建了一个使用视图合并关系的包:

https://github.com/staudenmeir/laravel-merged-relations

首先,在迁移中创建合并视图:

代码语言:javascript
复制
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'competitions',
    [(new YourModel)->CompetitionsHome(), (new YourModel)->CompetitionsGuest()]
);

然后定义关系:

代码语言:javascript
复制
class YourModel extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function competitions()
    {
        return $this->mergedRelationWithModel(Competition::class, 'competitions');
    }
}

像使用任何其他关系一样使用它:

代码语言:javascript
复制
$model->competitions;

$model->competitions()->paginate();

YourModel::with('competitions')->get();
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24184069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档