简体   繁体   English

从父id获取兄弟姐妹并排除自己的Laravel关系

[英]Get siblings from parent id and exclude itself Laravel relationship

CONTEXT语境

I am managing products.我在管理产品。 This is a shoe store.这是一家鞋店。 I would like to offer a view of the other variants.我想提供其他变体的视图。

The database is shaped like this:数据库的形状是这样的:

在此处输入图片说明

For example you can have a leather shoe (id 1), and there is 3 variants of this shoe: a black (id 1), a brown (id 2), and a grey (id 3).例如,您可以拥有一双皮鞋 (id 1),该鞋有 3 种变体:黑色 (id 1)、棕色 (id 2) 和灰色 (id 3)。

What I try to do is to construct a Laravel relationship to be able, from one variant, to get its siblings.我试图做的是构建一个 Laravel 关系,以便能够从一个变体中获得它的兄弟姐妹。 Here is what it looks like in the database according to the example I mentioned.这是根据我提到的示例在数据库中的样子。

SHOE
id
====
1

SHOE_VARIANT
id  shoeId  colorId
===================
1   1       1
2   1       2
3   1       3
...
8   2       5
9   3       2
10  3       4

In this case, if the user is viewing the black variant (id 1), I whish I could show him the 2 others variants (brown, id 2, and grey, id 3).在这种情况下,如果用户正在查看黑色变体(id 1),我希望我可以向他展示其他 2 个变体(棕色,id 2 和灰色,id 3)。

QUESTION

How can I construct a Laravel relationship in order to retrieve siblings from a parent id, and make sure the current record itself is not included?如何构建 Laravel 关系以从父 ID 检索兄弟姐妹,并确保不包含当前记录本身?

EXPERIMENTS实验

I already tried to construct a relationship like below, but the current record itself is included and I can't figure out how to exclude the record itself because I did not find how to get the current id of the record.我已经尝试构建如下关系,但是包含当前记录本身,我无法弄清楚如何排除记录本身,因为我没有找到如何获取记录的当前 id。

// app/ShoeVariant.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShoeVariant extends Model {
  public function siblings() {
    return $this->hasMany("App\ShoeVariant", "shoeId", "shoeId");
  }
}

This means:这意味着:

For the current shoe variant, get the shoe variants that matches knowing that you should match the foreign column named "shoeId" and the local column named "shoeId"对于当前的鞋子变体,获取匹配的鞋子变体,知道您应该匹配名为“shoeId”的外部列和名为“shoeId”的本地列

So if 2 shoe variants share the same column "shoeId", this works.因此,如果 2 个鞋子变体共享同一列“shoeId”,则此方法有效。 Stuck in excluding the current record from these results.坚持从这些结果中排除当前记录。

This should do what you want:这应该做你想做的:

public function siblings() {
    return $this->hasMany('App\ShoeVariant', 'shoeId', 'shoeId')
                ->where('id', '!=', $this->id);
}

Just filter out the current variant by id and get all the others.只需按 id 过滤掉当前变体并获取所有其他变体。

Alternatively, you can just make a new property:或者,您可以创建一个新属性:

public function getVariantsAttribute() {
    return $this->siblings->reject(function($elem) {
       return $elem->id == $this->id;
    });
}

And then use it in code like:然后在代码中使用它,如:

$variants = $model->variants; // all except this one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM