How to select foreign key value in Laravel - php

I've two tables one is car_category having the fields - id,type.
Another table named vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany('Vehicle');
}
}
vehicle model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo('Car');
}
}
What 'll be my query for this? I've tried this code, results error.
$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
WHERE cars.id = vehicles.c_id";
How can I achieve this? Can anybody help me?

Try this
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(Vehicle::class, 'c_id');
}
}
The vehicle model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method
https://laravel.com/docs/5.5/eloquent-relationships#one-to-one
To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();

To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();
One more correction you have specified class name as string literals without specifying FQN, relationships in models should be defined using fully qualified name
Car Model
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(\App\Models\Vehicle::class);
}
}
Vehicle Model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(\App\Models\Car::class);
}
}

Change from class car to class Car
After that you can select with Car::first(), the related table data can be found in Car::first()->vehicles
You can also add a where() method on models, if you have more than one record, use a foreach()

In Model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
In controller,
$vehicles = Vehicle::all();
return view('vehicles.vehicle',['vehicles'=>$vehicles]);

Related

Laravel eloquent with() returns null

namespace App;
use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
protected $table = "bid";
protected $primaryKey = 'bid_id';
protected $guarded = [];
protected $with = ['services'];
public function services() {
return $this->hasMany(Service::class, 'bid_id');
}
public function area() {
return $this->belongsTo(Area::class, 'area_id', 'area_id');
}
}
namespace App\Model\Service;
use Illuminate\Database\Eloquent\Model;
class Area extends Model
{
protected $table = "location_area";
protected $primaryKey = 'area_id';
protected $guarded = [];
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
}
Area table Migration and data
Bid table Migration and data
When I am trying to access
Bid::with('area')->find(BID_ID);
It is returning Null
Query is firing wrong:
"select * from `location_area` where `location_area`.`area_id` in (0)"
But if I am doing like:
$bid = Bid::find(BID_ID);
dd($bid->area);
It returns Area table values. What is going wrong? Please Help me. I
am having this problem for a long time. Thank You in advance :)
you must be declared a method in your MID model
public function area()
{
return $this->belongsTo(Area::class, 'bid');
}
something like this
after this, you access area in with()
Bid::with('area')->find(BID_ID);
Change this function in your Bid model :
public function area() {
return $this->belongsTo(Area::class, 'area_id');
}

Laravel - Where on relation from different database

I am trying to apply where condition on joined table, but I'm getting this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cts.plant' doesn't exist (SQL: select * from tbl_complaint where exists (select * from tbl_plant where tbl_complaint.made_in_plant = tbl_plant.plant_id and sap_code = 99999) order by created desc limit 50 offset 0)
My model classes looks something like this:
Main Model
class Complaint extends Model {
protected $connection= 'first';
protected $table = 'complaint';
protected $primaryKey = 'complaint_id';
public function customerPlant() {
return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
->select('plant_id', 'sap_code', 'plant_name');
}
}
Connected Model
class Plant extends Model {
protected $connection= 'second';
protected $table = 'plant';
protected $primaryKey = 'plant_id';
public function getKeyName() {
return 'plant_id';
}
}
Data retrieval:
$query = Complaint::with([
'madeInPlantId']
$query = Complaint::whereHas('madeInPlant', function($query){
$query->where('sap_code','=','99999');
});
$query->get();
I think that problem is I'm not specifying that connected table is in another database.
if your tables are on the same server but different databases, you can do this.
class Complaint extends Model {
protected $table = 'cts.complaint';
protected $primaryKey = 'complaint_id';
public function customerPlant(){
return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
->select('plant_id', 'sap_code', 'plant_name');
}
}
class Plant extends Model{
protected $table = 'otherdatabase.plant';
protected $primaryKey = 'plant_id';
public function getKeyName() {
return 'plant_id';
}
}

Laravel 5.4 Relationship hasMany not working

i have 2 model Article and ArtCategories
I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake?
.
Code model
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function Article(){
return $this->hasMany(Article::class);
}
}
class Article extends Model
{
protected $table = 'pjt_article';
protected $primaryKey = 'article_id';
protected $fillable = ['article_id','title','descriptions','username','cate_id','status','visit','reference'];
public function ArtCategories(){
return $this->belongsTo(ArtCategories::class,'cate_id');
}
public function admin(){
return $this->belongsTo(Admin::class);
}
}
This is DB structure Table up is pjt_article ,table down is pjt_categories_article
Result
$art = Article::findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
Relation Not working
You should add foreign key in relation method of ArtCategories
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function article(){
return $this->hasMany(Article::class, 'cate_id');
}
}
Now fetch article with ArtCategories as:
$art = Article::with('ArtCategories')->findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
As laravel convention Article() method should be articles() and ArtCategories() should be artCategory().

How to get the relation in laravel

I have three model : Manager ,Vendor, Banquet
and the relationship is :
manager has one vendor
vendor has many banquet
How to get the all manager with all relation in laravel orm?
$manager = Manager::where('active',1)->get();
$vendor = $manager->vendor()->get();// -- dose not work!
$banquet = $vendor->banquet()->get();// -- dose not work!
Manager model:
class Manager extends Model{
protected $table = 'manager';
protected $primaryKey = 'id';
public function vendor(){
return $this->hasOne('ACME\Entities\Vendor','managerId','id');
}
}
Here is the model
Vendor model:
class Vendor extends Model{
protected $table = 'vendor';
protected $primaryKey = 'id';
public function manager(){
return $this->belongsTo('ACME\Entities\Manager_V','id','managerId');
}
public function banquet(){
return $this->hasMany('ACME\Entities\V_Banquet' ,'vendorId' ,'id');
}
}
Banquet model:
class Banquet extends Model{
protected $table = 'banquet';
protected $primaryKey ='id';
public function vendor()
{
return $this->belongsTo('ACME\Entities\Vendor' ,'vendorId' ,'id');
}
}
That didn't work because get() gives the collection of managers. Vendor hasmany banquets so, banquets() in vendor model would be good convention. And You should do something like this:
$managers = Manager::where('active',1)->with('vendor','vendor.banquets')->get();
foreach($managers as $manager)
{
$vendor=$manager->vendor;
print_r($vendor);
foreach($vendor->banquets as $banquet)
{
print_r($banquet);
}
}
Use with method
$manager = Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
You will be able to get data as
$banquet = $manager->vendor->banquet;
// $banquet will be array of banquet model objects
Remember hasMany return array, hasOne return Object and belongsTo return Object.

belongsTo method returning null

I have two model one named Customer second one is Website
Relationship between them is, Customer hasMany Website while Website belongsTo Customer
This is how I am doing this
class Website extends \Eloquent {
use SubscriptionBillableTrait;
protected $fillable = [];
protected $guarded = ['id'];
public function customermodel()
{
// Return an Eloquent relationship.
return $this->belongsTo('Customer')
}
}
Customer model
use Mmanos\Billing\CustomerBillableTrait;
class Customer extends \Eloquent {
use CustomerBillableTrait;
protected $fillable = [];
protected $guarded = ['id'];
public function websites() {
return $this->hasMany('Website');
}
}
When I try to access Customer by relationship like this
$website = Website::find(1);
return dd($website->customermodel);
It returns null
Note:I am using Laravel 4
Use this
$website = Website::find(1)->with('customermodel');
return dd($website->customermodel);

Categories