Relations in Laravel eloquent - php

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.

Related

How to get data to table that has many relationships in Eloquent

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();

Laravel eloquent relationship for finding multilevel array

I am a beginner in laravel i want to create a nested api in which one model is connected with another using hasmany relationship here it is:
Model 1:
class Project extends Model
{
use HasFactory;
protected $table = 'projects';
public $timestamps = true;
protected $fillable = [
'title','description'
];
function categorywithqestions()
{
return $this->hasMany('App\Models\questionmd','cat','id');
}
}
Model 2:
class questionmd extends Model
{
use HasFactory;
protected $table = 'questions';
public $timestamps = true;
protected $fillable = [
'title',
'description',
'cat',
'q_type',
];
function relatedquestions()
{
return $this->hasMany('App\Models\relatedquestion','question_id','id');
}
}
Model 3:
class relatedquestion extends Model
{
use HasFactory;
protected $table = 'related_questions';
public $timestamps = true;
protected $fillable = [
'question_id',
'title',
'description',
];
}
and here is controller:
$callback = function($query) {
$query->where('q_type', '=', 'direct_ask');
};
$questionmd = Project::whereHas('categorywithqestions', $callback)
->with(['categorywithqestions' => $callback])->get();
return response()->json(['message' => 'Success', 'status' => 200,'data'=>$questionmd]);
I want to fetch the related questions also inside the "categorywithqestions" how to do it?
From what i see, you can use hasManyThrough helper.
The database structure should be like this.
1 Project hasMany categories
1 Category hasMany questions
projects
id - integer
name - string
categories
id - integer
project_id - integer
name - string
questions
id - integer
category_id- integer
commit_hash - string
on Project model you can do like this
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
/**
* Get all of the deployments for the project.
*/
public function deployments()
{
return $this->hasManyThrough(Deployment::class, Environment::class);
}
}
later on in you queries you can make
$questions = Project::all()->load('questions');
Please try this way.
$questionmd = Project::whereHas('categorywithqestions', function($q) {
$q->where('q_type', '=', 'direct_ask');
})->with(['categorywithqestions.relatedquestions'])->get();

how to access a function from model file

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'));
}

How to display data from different data tables? One to many reationship

So, I have Model who has many uploaded Videos. Model and models_videos are different tables. I need to display video from each model based on their id.
ModelController:
public function index()
{
$models = NewModel::all();
$model_video = NewModelVideos::all();
return view('admin.model_new_videos.index')
->with('models', $models)
->with('model_video', $model_video);
}
Models
class NewModel extends Model
{
protected $table = 'models';
protected $guarded = ['id'];
protected $sortable = ['id', 'name', 'about'];
public function videos()
{
return $this->hasMany('App\Models\NewModels\NewModelVideos','model_id' ,'id');
}
}
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->belongsTo('App\Models\NewModels\NewModel', 'id');
}
}
And View:
#foreach($model_video as $model)
<h1>{{ $model->title }} </h1>
{{ $model->video }}
#endforeach
I can't get video which belongs to specific model. Sorry, I am new and still learning
I think you have to specify the column what is related to NewModel:
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->belongsTo('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
}
}
If you did not specified a foreign key for the models: here is what docs says One To One
Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the user's id column in the user_id column of the Phone record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
That is mean that you can do it this way too:
class NewModelVideos extends Model
{
use Sortable;
protected $table = 'models_videos';
protected $guarded = ['id'];
protected $sortable = ['id', 'model_id', 'title', 'video'];
public function model()
{
return $this->hasOne('App\Models\NewModels\NewModel', 'id', 'model_id'); //<-- here
}
}

Laravel Relationship's

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;

Categories