I have a little difficulty in Laravel Relationships. I made all the relationships between CourseModel, CourseTimeModel and CourseInstructorModel. But the problem is that i want to get instructor_name from instructor table. Is it possible that i can get the instructor_name from instructor table using relationship?
CourseModel.php
class CourseModel extends Model {
protected $table = 'course';
protected $fillable = [
'course_name',
'fee',
'duration',
'description',
'created_at',
'updated_at',
];
public function courseInstructor() {
return $this->hasMany('App\CourseInstructorModel');
}
public function courseTime() {
return $this->hasMany('App\CourseTimeModel');
}
public function getCourses() {
$courses = $this->with(['courseTime', 'courseInstructor'])->paginate(10);
return $courses;
}
}
CourseInstructorModel.php
class CourseInstructorModel extends Model
{
protected $table = 'course_instructor';
protected $fillable = [
'course_id',
'instructor_id',
'created_at',
'updated_at',
];
public function course()
{
return $this->belongsTo('App\CourseModel');
}
}
CourseTimeModel.php
class CourseTimeModel extends Model
{
protected $table = 'course_time';
protected $fillable = [
'course_time',
'course_id',
'created_at',
'updated_at',
];
public function course()
{
return $this->belongsTo('App\CourseModel');
}
}
I solved my problem using Many to Many Relationship between CourseModel and InstructorModel.
Here is my code that i write in CourseModel.php
public function instructor() {
return $this->belongsToMany('App\Instructor');
}
You can get instructor_name in this way :
$courseModel = CourseModel::find(1);
$instructor_name = $courseModel->courseInstructor->instructor_name;
Related
I am trying to work on an eloquent model Post where it has two hasOne relationships: offer_post and request_post.
Post.php
class Post extends Model
{
use HasFactory;
protected $table = 'tbl_post';
protected $fillable = ['email', 'postIdentity', 'postStatus'];
public $timestamps = false;
public $primaryKey = 'indexPost';
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->postNumber = (string) Uuid::generate(4);
});
}
public function pasabuy_user() {
$this->belongsTo(PasabuyUser::class, 'email', 'email');
}
public function offer_post() {
return $this->hasOne(OfferPost::class, 'postNumber', 'postNumber');
}
public function request_post() {
return $this->hasOne(RequestPost::class, 'postNumber', 'postNumber');
}
}
OfferPost.php
class OfferPost extends Model
{
use HasFactory;
protected $table = 'tbl_shoppingOfferPost';
protected $fillable = ['postNumber', 'postStatus', 'deliveryArea', 'shoppingPlace', 'deliverySchedule', 'transportMode', 'capacity', 'paymentMethod', 'caption'];
public $timestamps = false;
public $primaryKey = 'indexShoppingOfferPost';
public function post() {
return $this->belongsTo(Post::class, 'postNumber', 'postNumber');
}
}
RequestPost.php
class RequestPost extends Model
{
use HasFactory;
protected $table = 'tbl_orderRequestPost';
protected $fillable = [
'postNumber',
'postStatus',
'deliveryAddress',
'shoppingPlace',
'deliverySchedule',
'paymentMethod',
'shoppingList',
'caption'
];
public $timestamps = false;
public $primaryKey = 'indexOrderRequestPost';
/**
* [post description]
* #author Al Vincent Musa
* #return [type] [description]
*/
public function post() {
return $this->belongsTo(Post::class, 'postNUmber', 'postNumber');
}
}
This is how my tables looks like.
Now I want to get all post(both offer post and request post)
Get offer post like
SELECT from tbl_post INNER JOIN tbl_shoppingOfferPost ON tbl_post.postNumber = tbl_shoppingOfferPost.postNumber
and likewise for the request post.
I came as far as
$post = Post::has('offer_post')->get();
but this only returns data from tbl_post. But want both from tbl_post and tbl_shoppingOfferPost.
I am having a hard time understanding the docs. I don't know where to start. Any help is much appreciated. I just need a pointer where to look at. Thanks
You can do like this
$post::with(['offer_post','request_post'])->get();
im using laravel 7.24 and php 7.4 on my project
What i want to is fundementally creating relations between 3 table and using them in 'one' query.
to be specific i need to access 'ordered products' from my order detail page.
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = CertainOrder::with('ShoppingCard.shoppingCardProducts.product')
->where('ShoppingCard.id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
CertainOrder model access to 'ShoppingCard' model from top and in the ShoppingCard model it contains shoppingCardProducts function which you will see in below and with shoppingCardProducts function my 'products' table had a relation. the problem is something in relations is wrong and i can't get data from shoppingcardproduct
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo(ShoppingCard::class, 'sepet_id');
//sepet_id is a foreign key.
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function product()
{
return $this->belongsTo('App\Product');
}
I think you missed it somewhere in the code
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
public function CertainOrder(){
return $this->hasMany('path\to\model');
}
public function ShoppingCardProduct(){
return $this->hasMany('path\to\model');
}
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo('App\path\to\model', 'sepet_id');
//sepet_id is a foreign key.
}
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function ShoppingCard()
{
return $this->belongsTo('App\ShoppingCard');
}
}
and make the call this way
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = ShoppingCard::with('CertainOrder, ShoppingCardProduct')
->where('id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code:
Dish.php
class Dish extends Model
{
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'description', 'enable'];
public $timestamps = false;
public function components()
{
return $this->hasManyThrough('App\DishValues', 'App\Dish', 'id', 'dishes_id');
}
}
DishValues
class DishValues extends Model
{
protected $quarded = ['id'];
protected $fillable = ['dishes_id', 'food_ingredient_id', 'quantity'];
public $timestamps = false;
public function ingredient()
{
return $this->belongsTo('App\FoodIngredient', 'food_ingredient_id');
}
}
FoodIngredient.php
class FoodIngredient extends Model
{
use scopeActiveTrait;
public function scopeVisibleDemo($query)
{
return $query->where('available_in_demo', 1);
}
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'garbage', 'energy_value', 'protein', 'fat', 'available_carbohydrates', 'roughage', 'description', 'url_address', 'allergen', 'available_in_demo', 'enable'];
public $timestamps = false;
}
I get my data:
Dish::with('components')->paginate(25);
How can I get in this code values from FoodIngredient?
This is not working:
Dish::with('components, ingredient')->paginate(25);
or
Dish::with('components')->with('ingredient')->paginate(25);
Given you have multiple relationships, you use :with() with an array of values, not a comma separated string.
This example comes from the docs on "Eager Loading Multiple Relationships" and I've re-named the models based on your example
App\Dish::with(['components', 'ingredient'])->get();
There is also a good blog post that explores the eager/lazy loading of related models in this way.
I have worked a lot with Laravel and never got the following error:
Call to a member function getQuery() on null at /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php line 558.
I'm trying to get a record with all the relationships specified. The code that is causing that error is the following:
$id = 7;
$compra = Compra::where('id', $id)
->with(['certificado',
'certificado.duracionServicios',
'certificado.duracionServicios.servicio',
'certificado.duracionServicios.servicio.traducciones' => function($query){
$query->whereHas('idiomas', function($q){
$q->where('codigo_region', 'es_MX');
});
},
'user'])
->first();
If I take out the first() method, I can print the object instance of Builder, but when I try to use it or even use get(), that exception is thrown. Laravel version I'm using is 5.5.
Model Compra
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class Compra extends Model
{
protected $table = 'compras';
protected $fillable = ['folio',
'fecha_compra',
'subtotal',
'total',
'user_id',
'direccion_id',
];
protected $dates = ['created_at', 'updated_at'];
/**
* Get the value of the model's route key.
*
* #return mixed
*/
public function getRouteKey()
{
$hashids = new \Hashids\Hashids(config('app.name'), 5);
return $hashids->encode($this->getKey());
}
public function certificado(){
$this->hasOne('App\Models\Sitio\Certificado', 'compra_id');
}
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
Model Certificado
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class Certificado extends Model
{
protected $table = 'certificados';
protected $fillable = ['fecha_servicio',
'hora_servicio',
'compra_id',
];
protected $dates = ['created_at', 'updated_at'];
public function compra(){
return $this->belongsTo('App\Models\Sitio\Compra', 'compra_id');
}
public function duracionServicios(){
return $this->belongsToMany('App\Models\Sitio\DuracionServicio', 'certificados_duracion_servicios', 'certificado_id', 'duracion_id');
}
}
Model DuracionServicio
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class DuracionServicio extends Model
{
protected $table = 'duracion_servicios';
protected $fillable = ['costo',
'servicio_id',
];
protected $dates = ['created_at', 'updated_at'];
public function certificados(){
return $this->belongsToMany('App\Http\Models\Sitio\Certificado', 'certificados_duracion_servicios', 'duracion_id', 'certificado_id');
}
public function servicio(){
return $this->belongsTo('App\Models\Sitio\Servicio', 'servicio_id');
}
public function traducciones(){
return $this->hasMany('App\Models\Sitio\DuracionServicioTraduccion', 'duracion_id');
}
}
Model Servicio
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class Servicio extends Model
{
protected $table = 'servicios';
protected $fillable = ['seccion_id'];
protected $dates = ['created_at', 'updated_at'];
public function traducciones(){
return $this->hasMany('App\Models\Sitio\ServicioTraduccion', 'servicio_id');
}
public function duraciones(){
return $this->hasMany('App\Models\Sitio\DuracionServicio', 'servicio_id');
}
}
Model ServicioTraduccion
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class ServicioTraduccion extends Model
{
protected $table = 'servicios_traducciones';
protected $fillable = ['nombre',
'descripcion',
'contenido',
'idioma_id',
'servicio_id',
];
protected $dates = ['created_at', 'updated_at'];
public function servicio(){
return $this->belongsTo('App\Models\Sitio\Servicio', 'servicio_id');
}
public function idioma(){
return $this->belongsTo('App\Models\Sitio\Idioma', 'idioma_id');
}
}
Model Idioma
namespace App\Models\Sitio;
use Illuminate\Database\Eloquent\Model;
class Idioma extends Model
{
protected $table = 'servicios_traducciones';
protected $fillable = ['nombre',
'codigo_region',
];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
public function servicios(){
return $this->hasMany('App\Models\Sitio\ServicioTraduccion', 'idioma_id');
}
public function duraciones(){
return $this->hasMany('App\Models\Sitio\DuracionServicioTraduccion', 'idioma_id');
}
}
Ok, so the problem is in your Compra model.
You defined relationship like this:
public function certificado()
{
$this->hasOne('App\Models\Sitio\Certificado', 'compra_id');
}
You forgot to add return. It should be:
public function certificado()
{
return $this->hasOne('App\Models\Sitio\Certificado', 'compra_id');
}
You can't call get_query() on a ->first().
->first() will return the first result of your query, and so execute the SQL query (after the first() you get a null result if no result, or your query result object). You should be able to use get_query() or get() if you remove the first() as you'll have an eloquent query instance, not a result object or collection.
You need to build up a query here by calling the query() method first.
$id = 7;
$compra = Compra::query()->where('id', $id)
->with(['certificado',
'certificado.duracionServicios',
'certificado.duracionServicios.servicio',
'certificado.duracionServicios.servicio.traducciones' => function($query){
$query->whereHas('idiomas', function($q){
$q->where('codigo_region', 'es_MX');
});
},
'user'])
->get();
or you can use ->first();
I'm using laravel 5.4, have two models ParentAccount and ChildAccount,
A parent has many childs
Parent
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ParentAccount extends Model
{
//
public $timestamps = false;
protected $table = 'parent_accounts';
protected $fillable = [
'name', 'account_id'
];
public function childs()
{
return $this->hasMany('App\ChildAccount','account_id', 'parent_id');
}
}
child
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ChildAccount extends Model
{
//
public $timestamps = false;
protected $table = 'child_accounts';
protected $fillable = [
'name', 'account_id','parent_id'
];
}
When i use echo ParentAccount::find(1)->childs();
i get an error Call to a member function childs() on null although all parents have children
Note: child has parent_id where it's the account_id in the parent
in parent model
public function childs(){
return $this->hasMany(ChildAccount::class, 'parent_id' , 'account_id');
}
in child model
public function parent(){
return $this->belongsTo(ParentAccount::class, 'parent_id' , 'account_id');
Edited Code
public function childs()
{
return $this->hasMany('App\ChildAccount', 'parent_id','account_id');
}
The relation function must be in the format
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}
First you have to add the primaryKey property then change the relation parameters and add the revers relation to the ChildAccount :
ParentAccount :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ParentAccount extends Model
{
protected $primaryKey = 'account_id';
public $timestamps = false;
protected $table = 'parent_accounts';
protected $fillable = [
'name', 'account_id'
];
public function childs()
{
// 'foreign_key', 'local_key'
return $this->hasMany('App\ChildAccount', 'parent_id', 'account_id');
}
}
ChildAccount :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ChildAccount extends Model
{
protected $primaryKey = 'account_id';
public $timestamps = false;
protected $table = 'child_accounts';
protected $fillable = [
'name', 'account_id','parent_id'
];
public function parent() {
// foreign_key, 'other_key'
return $this->belongsTo('App\ParentAccount', 'parent_id', 'account_id');
}
}
With doing that you can get the childs :
ParentAccount::find(1)->childs;
You got Call to a member function childs() on null because ParentAccount::find(1) return null. Make sure you have ParentAccount with id=1 in your DB.
You need to change keys order like this:
public function childs()
{
return $this->hasMany('App\ChildAccount', 'parent_id', 'account_id');
}