【问题标题】:How do I create a hasMany relationship with non-standard foreign keys如何使用非标准外键创建 hasMany 关系
【发布时间】:2021-04-10 14:34:22
【问题描述】:

我有一个 Laravel 8 应用程序,其中 User hasMany Notificationsnotifications 表有两个必需的键:sender_idrecipient_id。这些都是User 的实例。以下是我在模型中设置关系的方法:

App\Models\User

 public function recievedNotifications()
 {
     return $this->hasMany(Notification::class, 'recipient_id');
 }

 public function sentNotifications()
 {
     return $this->hasMany(Notification::class, 'sender_id');
 }

App\Models\Notification

  public function recipient()
  {
      return $this->belongsTo(User::class);
  }

  public function sender()
  {
      return $this->belongsTo(User::class);
  }

我想创建两个用户并为这两个用户正确关联Notification 实例。我不太明白语法。

我想尝试这样的事情,但是当我手动查看数据库条目时它分配了不正确的用户 ID:

$sender = User::factory()->create();
$recipient = User::factory()->create();

$notification = App\Models\Notification::factory()->hasSender($sender)->hasRecipient($recipient)->create();

我不确定这是否是以下功能:

1:没有在 PHP 模型中设置关系 2:没有以正确的方式创建工厂

Notification 工厂定义如下:

<?php

namespace Database\Factories;

use App\Models\Notification;
use Illuminate\Database\Eloquent\Factories\Factory;

class NotificationFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Notification::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'message'        => $this->faker->sentence,
            'is_read'        => rand(0, 1),
        ];
    }
}

如何使用工厂正确地为收件人和发件人创建通知?

【问题讨论】:

  • Laravel 中的所有关系方法(hasOne()belongsTo()hasMany()belongsToMany())都可以自定义为使用与假设不同的列(id、@987654341 @, 等等)。只需检查文档并根据需要更新您的方法:laravel.com/docs/8.x/…hasOne(Model::class, 'foreign_key', 'local_key');belongsTo(Model::class, 'foreign_key', 'owner_key');hasMany(Model::class, 'foreign_key', 'local_key');belongsToMany(Model::class, 'pivot_table', 'foreign_key', 'local_key');;在Notifications 模型上

标签: php laravel eloquent laravel-8


【解决方案1】:

关系看起来不错,所以我倾向于不正确使用工厂。如果您没有明确提供属性,工厂只是提供在实例化新模型时使用的默认值。

您可以通过在create()make() 方法中提供一个数组来设置这些值:

$sender = User::factory()->create();
$recipient = User::factory()->create();

$notification = Notification::factory()->create([
    'sender_id' => $sender->getKey(),
    'recipient_id' => $recipient->getKey(),
]);

【讨论】:

    【解决方案2】:

    为什么不直接使用它,从工厂分配 id?

    $sender = User::factory()->create();
    $recipient = User::factory()->create();
    
    $notification = App\Models\Notification::factory()->create([
        'recipient_id' => $recipient->id,
        'sender_id'    => $sender->id
    ]);
    

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 2019-08-29
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多