简体   繁体   中英

How to store primary id in another table using laravel mvc?

Earlier i was working on core php and currently i shift to laravel and mvc. So i dont know much about mvc and laravel too. I am facing one issue.Help me to solve this.

I have 2 tables:

  1. companies
  2. company_address

model for companies:

class Company extends Eloquent {

    protected $fillable = [
                            'name',
                            'email',
                            'website',
                            'logo',
                            'phone',

                        ];
    protected $primaryKey = 'id';
    protected $table = 'companies';
}

model for company_address:

class Companyaddress extends Eloquent {

    protected $fillable = [
                            'companies_id',
                            'address_line_1',
                            'address_line_2',
                            'city',
                            'state',
                            'zipcode',
                            'country_id',                           
                        ];
    protected $primaryKey = 'id';
    protected $table = 'company_address';
}

my controller to save this two tables:

public function store(CompanyRequest $request, Company $company, Companyaddress $companyaddress){   

        if(!Entrust::can('create-company'))
            return response()->json(['message' => trans('messages.permission_denied'), 'status' => 'error']);

        $data = $request->all();
        $company->fill($data)->save();
        $companyaddress->fill($data)->save();
        storeCustomField($this->form,$company->id, $data);

        $this->logActivity(['module' => 'company_address','module_id' => $company->id,'activity' => 'added']);

        return response()->json(['message' => trans('messages.company').' '.trans('messages.added'), 'status' => 'success']);
    }

My code works fine. on submit i can able to store data as per my models. I want to store company tables primary key in company_address table as foreign key.so in future i can show address of particular company. how to done it?

A good way to do this is to define a relationship between the two using eloquent relationships. See:

https://laravel.com/docs/5.4/eloquent-relationships

First, define a relationship on the Company model:

public function address()
{
    return $this->hasOne(Companyaddress:class);
}

Then in your controller, you can do something like:

$company = Company::create($data);
$company_address = Companyaddress::create($data);


$company->address()->save($company_address);

just place this before the $data variable definition. (Since you already have the $company collection set)

$request->merge(['companies_id'=>$company->id]);

before $companyaddress. Also there is no need for the $data variable (IMHO)

Set Company Id before saving company address:

$data->companies_id = $company->id;

or

$data['companies_id '] = $company->id;

Store Method:

public function store(CompanyRequest $request, Company $company, Companyaddress $companyaddress){   

        if(!Entrust::can('create-company'))
            return response()->json(['message' => trans('messages.permission_denied'), 'status' => 'error']);

        $data = $request->all();
        $company->fill($data)->save();
        $data->companies_id = $company->id; //Set company id here
        $companyaddress->fill($data)->save();
        storeCustomField($this->form,$company->id, $data);

        $this->logActivity(['module' => 'company_address','module_id' => $company->id,'activity' => 'added']);

        return response()->json(['message' => trans('messages.company').' '.trans('messages.added'), 'status' => 'success']);
    }

First add some relationships in your models by adding functions.

in your Company model.

class Company extends Eloquent {

    protected $fillable = [
                            'name',
                            'email',
                            'website',
                            'logo',
                            'phone',

                        ];
    protected $primaryKey = 'id';
    protected $table = 'companies';

    public function companyAddress() 
    {
       return $this->hasOne('App\CompanyAddress');
    }
}

in your CompanyAddress model.

class Companyaddress extends Eloquent {

    protected $fillable = [
                            'companies_id',
                            'address_line_1',
                            'address_line_2',
                            'city',
                            'state',
                            'zipcode',
                            'country_id',                           
                        ];
    protected $primaryKey = 'id';
    protected $table = 'company_address';

    public function companyAddress() 
    {
      return $this->belongsTo('App\Company');
    }
}

Then in your Controller.

y'can add this code in your method. After the save() method to the "companies" table, get the last inserted ID, assuming your primary key is auto increment.

$companyAddress = new CompanyAddress;
$companyAddress->companies_id = $data->id;

$companyAddress->save();

You look up to this documentation as reference: https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Relations.html

Or maybe you can get info here: Laravel, get last insert id using Eloquent

In your case, if one company has one address, you should combine it into one table. But if you need to, here:

Model Company.php

class Company extends Eloquent {
protected $fillable = [
                        'id',
                        'name',
                        'email',
                        'website',
                        'logo',
                        'phone',

                    ];
protected $primaryKey = 'id';
protected $table = 'companies';

public function address(){
  $this->hasOne(CompanyAddress::class,'company_id','id')
}
}

Model CompanyAddress.php

class CompanyAddress extends Eloquent {

protected $fillable = [
                        'company_id',
                        'address_line_1',
                        'address_line_2',
                        'city',
                        'state',
                        'zipcode',
                        'country_id',                           
                    ];
protected $table = 'company_address';
}

In your controller

public function store(CompanyRequest $request, Company $company, Companyaddress $companyaddress){   

    if(!Entrust::can('create-company'))
        return response()->json(['message' => trans('messages.permission_denied'), 'status' => 'error']);

    $data = $request->all();
    $company->fill($data)->save();
    $data->company_id = $company->id;
    $companyaddress->fill($data)->save();


    $this->logActivity(['module' => 'company_address','module_id' => $company->id,'activity' => 'added']);

    return response()->json(['message' => trans('messages.company').' '.trans('messages.added'), 'status' => 'success']);
}

public function getCompany($id){
    $company = Company::find($id);
    $company->address;
    return $company->toArray();
}

and the result when you call getCompany($id)

{
    id : ...,
    name : ...,
    .
    .
    .
    address : {
               company_id: ...,
               address_line_1: ...,
               .
               .
               .
              }
}

Hope it's gonna help. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM