K
K
kaxa32012021-03-15 21:25:57
Laravel
kaxa3201, 2021-03-15 21:25:57

How to create a many-to-many relationship without a pivot table?

I am writing an api to which they come

$requestData = [
            "email"        => "[email protected]",
            "login"        => "test",
            "password" => "sdfsdf",
            "url_id"       =>   12
        ];


I want email to have multiple urls and multiple email urls
Wrote models
class Email extends Model
{
    use HasFactory;

    protected $fillable = [
        'email',
        'login',
        'password',
    ];

    public function urls()
    {
        return $this->belongsToMany(EmailUrl::class);
    }
}
class EmailUrl extends Model
{
    use HasFactory;
    protected $table = 'emails_urls';

    protected $fillable = [
        'url_id',
        'email_id',
    ];

    public function emails()
    {
        return $this->belongsToMany(Email::class);
    }
}

I wrote a script to create an entry, but I think that everything is wrong.
$requestData = [
            "email"    => "[email protected]",
            "login"    => "test",
            "password" => "sdfsdf",
            "url_id"   => 12,
        ];
        $email = Email::create([
            'email'    => $requestData['email'],
            'login'    => $requestData['login'],
            'password' => $requestData['password'],
        ]);
        $url = EmailUrl::create(['email_id' => $email->id, 'url_id' => $requestData['url_id']]);

Have I done this correctly? If not, please tell me how

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question