php laravel 插入多个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25136211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:40:49  来源:igfitidea点击:

laravel inserting into multiple tables

phplaravel

提问by dontHaveName

I have 2 tables

我有2张桌子

#something - id, name, url
#something_users - id, id_something, email, password

My models

我的模特

class Something extends Eloquent
{

    protected $table = 'something';

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

    public $errors;


    public function User()
    {
        return $this->belongsTo('User', 'id', 'id_something');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    protected $table = 'something_users';

    protected $hidden = array('password', 'remember_token');

    public function Something()
    {
        return $this->belongsTo('Something');
    }

}

Controller

控制器

$input = Input::all();

// also some validation
$this->db->fill($input);

$this->db->password = Hash::make(Input::get('password'));

$this->db->push();

$this->db->save();

SQL

SQL

insert into `something` (`name`, `email`, `password`) values...

I need to insert name into the first table(something) and email, password into second(something_users)

我需要将名称插入第一个表(某物)和电子邮件,密码插入第二个(某物_用户)

How to do that? I have on clue about that.

怎么做?我对此有所了解。

回答by user1669496

Your relationships are a little screwed up, you probably want to change those. Note the hasMany()vs the belongsTo(). If a somethingcan only have one user, you may wish to change the function to hasOne()from hasMany()and the name of the function to user()only because it makes more sense that way.

你的关系有点搞砸了,你可能想改变它们。注意hasMany()vs belongsTo()。如果 asomething只能有一个user,您可能希望将函数更改为hasOne()fromhasMany()并将函数名称更改为user()only ,因为这样更有意义。

class Something extends Eloquent {

    protected $table = 'something';

    public function users()
    {
        return $this->hasMany('User', 'id_something');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $table = 'something_users';

    protected $hidden = array('password', 'remember_token');

    public function something()
    {
        return $this->belongsTo('Something', 'id_something');
    }
}

And then to save a somethingand a userand have them linked, it's pretty easy.

然后保存 asomething和 auser并将它们链接起来,这很容易。

$something = new Something;
$something->name = Input::get('name');
$something->url = Input::get('url');
$something->save();

$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));

$something->users()->save($user);

I'm not seeing your constructor so I don't know which model $this->dbrefers to, but you may want to replace the somethingsor usersdepending on what you have. To keep your dependency injection going, I'd suggest naming your dependencies what they actually are.

我没有看到你的构造函数,所以我不知道哪个模型$this->db指的是,但你可能想要替换somethingsusers取决于你有什么。为了让您的依赖注入继续进行,我建议您将依赖项命名为它们的实际名称。

class SomeController extends BaseController {

    public function __construct(User $user, Something $something)
    {
        $this->user = $user;
        $this->something = $something;
    }

    public function someFunction()
    {
        $this->something->name = Input::get('name');
        $this->something->url = Input::get('url');
        $this->something->save();

        $this->user->email = Input::get('email');
        $this->user->password = Hash::make(Input::get('password'));
        $this->something->users()->save($this->user);
    }
}

回答by Anonymouse

Laravel 6.

拉维尔 6.

I want to add data to users table and customer table using one controller that is RegisterController.

我想使用 RegisterController 控制器将数据添加到用户表和客户表。

<?php

 namespace App\Http\Controllers\Auth;

 use App\User;
 use App\Customer;
 use App\Http\Controllers\Controller;
 use App\Providers\RouteServiceProvider;
 use Illuminate\Foundation\Auth\RegistersUsers;
 use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Facades\Validator;

 class RegisterController extends Controller
 {
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/

use RegistersUsers;

/**
 * Where to redirect users after registration.
 *
 * @var string
 */
protected $redirectTo = RouteServiceProvider::HOME;

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest');
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */

//this part is my code
protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'role' => '2',
    ]);

    $customer = Customer::create([
        'user_id' => $user['id'],
        'firstname' => $data['name'],
        'lastname' => $data['name'],
        'email' => $data['email'],
        'address' => '',
        'phone' => '',
        'gender' => '',
    ]);

    return $user;
     }
 }

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

This answer is not the best one, because this answer is just a shortcut code so that my code is not error. maybe another error will appear in the future. but I hope my answer can solve your problem

这个答案不是最好的,因为这个答案只是一个快捷代码,所以我的代码不会出错。也许将来会出现另一个错误。但我希望我的回答能解决你的问题

回答by CM Woo

I have a similar problem. i have 2 table and saving data like these

我有一个类似的问题。我有 2 个表并保存这样的数据

usertable:

用户表:

 id, name, username, password, role

membertable:

成员表:

 member_id, member_ic, member_contact, addressType_id, address, postcode, state, user_id

I am able to add those data separately into the database but dunno how add it together like the example showing.....

我可以将这些数据分别添加到数据库中,但不知道如何像示例中显示的那样将它们添加在一起.....

Beside that, the data only will save when the role = 3 I am using the example framework from https://github.com/bestmomo/laravel5-example

除此之外,数据仅在角色 = 3 时才会保存我使用的是https://github.com/bestmomo/laravel5-example 中的示例框架

anyone can guide me on this thank you.

任何人都可以指导我,谢谢。