Laravel获取一对多关系

时间:2018-12-01 04:24:18

标签: laravel foreign-keys

您好,我正在学习laravel,但在从我的关系中检索数据时遇到问题。

在我的数据库中,“产品”和“组”充满了虚拟数据。

我在产品模型中这样定义了我的关系:

static volatile boolean stopLoop = false;
public static void main(String... args) throws Exception {
    Thread t = new Thread(() -> {
        while (true)  {
            String input = System.console().readLine();
            if (input.equals("!off")) {
                stopLoop = true;
            }
        }
    });
    t.start();

    while (!stopLoop) {
        // ...
    }
}

在我的小组中,反之亦然:

     public function Group()
        {
     return $this->hasMany('App\Groups','product_id', 'id');
      }

我引用我的产品表的方式是:

      public function Product()
      {
      return $this->belongsTo('App\Product','product_id', 'id');
      }

现在我在数据库中的“组”下有“ product_id”列,它是否链接到产品ID中。

groups表包含其自动递增的id和product_id外键列。

“产品”表的ID和名称列自动递增。

问题在这里: 如何返回组表中不为空或具有值(产品ID)的产品。


我在过滤器控制器中尝试过类似的操作:

     $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

但这给了我未定义关系的呼唤。

我不确定如何访问belongsTo或hasMany方法,以及我的产品表中是否需要额外的group_id列。

1 个答案:

答案 0 :(得分:1)

您将关系命名为错误。它应该为groups并以小写字母定义为

public function groups()
{
    return $this->hasMany('App\Groups','product_id', 'id');
}

并使用->has()检查是否存在

public function getProductsWithGroup()
{
    $Products = Product::has('groups')->get();
    return $Products ;
}

->with()用于增加负载,而->has()用于检查存在性过滤器

>

要获得没有任何组的产品,

$Products = Product::doesntHave('groups')->get();

要查看使用->has()检查的其他方法,请https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

相关问题