简体   繁体   中英

Laravel Eloquent ORM Relationships

I have a issue with Eloquent ORM relationship i have company Model and Countries Model, One to Many relationship, I have used following codes.

Company Model

    class Company_model extends Model
    {
        public $table = "company";
        public $primaryKey = "id";

        public function countries(){
            return $this->belongsTo('App\Models\Countries','country','countryId');
        }
    }

Countries Model

class Countries extends Model
{
    public $table = "countries";
    public $primaryKey = "countryId";


}

i have used the following code to retrieve the data i want to get company details along with countryName

$companyObj = new Company_model();

$result = $companyObj::with('countries')->get();

i get the results with company and countries details but the countries details come as an array i need it come without array also i need to take the country Name now all the details in the countries table comes to the array.

Now Result

Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [country] => 1 [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] =>  [countries] => Array ( [countryId] => 1 [countryName] => Test [currency] => [language] => ) ) ) 

I need the result like

Array ( [0] => Array ( [id] => 1 [companyName] => Test [address] => [phone] => [email] => [website] => [companyImg] => 1 [create_by] => [create_time] =>  [countryName] => Test  ) ) 

You've to add a new method in Company_model that's have the method that only give the selected fields.

class Company_model extends Model
    {
        public $table = "company";
        public $primaryKey = "id";

        public function countries(){
            return $this->belongsTo('App\Models\Countries','country','countryId');
        }
    }

This is the new method.

public function countriesIDs()
{
   return $this->belongsTo('App\Models\Countries')->select(['name']);
}

尝试这个

$result = $companyObj::with('countries')->get()->toArray();

You can to do this:

$result = Company_model::leftjoin('countries', 'countries.id', '=', 'company.countryId')->select('company.*', 'countries.countryName')->get();

I hope it would helpful.

It is not possible by laravel "with" query. You have to get it by join query like:

Company_model::join('countries','countries.countryId','=','company.country')->select('company.*','countries.countryName')->get();

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