【发布时间】:2021-04-10 14:34:22
【问题描述】:
我有一个 Laravel 8 应用程序,其中 User hasMany Notifications。 notifications 表有两个必需的键:sender_id 和 recipient_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