【问题标题】:Testing BelongsToMany relationship with pivot table使用数据透视表测试 BelongsToMany 关系
【发布时间】:2021-03-30 05:17:37
【问题描述】:

我正在尝试弄清楚如何根据 Laravel 中的这种关系测试来创建所有数据。

公司模式

class Company
{
    public function stores()
    {
        return $this->hasMany(Store::class, 'company_id');
    }

    public function employers()
    {
        return $this->belongsToMany(User::class, 'employers', 
            'company_id', 'user_id');
    }
}

商店模式

class Store
{
    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id');
    }

    public function employers()
    {
        return $this->belongsToMany(User::class, 'employers', 
            'store_id', 'user_id');
    }
}

用户模型

class User
{
    public function company()
    {
        return $this->belongsToMany(Company::class, 'employers', 
            'user_id', 'company_id');
    }

    public function store()
    {
        return $this->belongsToMany(Store::class, 'employers', 
            'user_id', 'store_id');
    }
}
$company = Company::factory()->hasStores(
    Store::factory()->hasEmployers(User::factory())
)->create();
dd($company) // App\Models\Company {#2470... Ok!

$store = $company->store()->first();
dd($store) // App\Models\Store {#2479... Ok!

$user = $store->employers()->first();
dd($user) // null (T-T)

背景:这是一个允许所有者拥有多家公司的应用程序。因此,我得到了很多关系,即使如此,员工有时也只能属于一个公司或商店。

【问题讨论】:

    标签: laravel eloquent laravel-8


    【解决方案1】:

    试试:

      $store = $company->store->first();
      dump($store);
      
      $user = $store->employers->first();
      dump($user);
    

    【讨论】:

    • 谢谢,但是我试过了,但是“雇主”是多对多的关系,如果我只调用$store->employers变成Eloquent\Collection,我需要调用“模型”$store->employers(),我想我错过了什么......顺便说一句,仍然是null
    猜你喜欢
    • 2015-10-16
    • 2014-12-15
    • 2018-09-26
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多