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
}
}
Related
I have 3 tables (workflow, user, workflow_user) and I would like to select the view column of the workflow_user table.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class,'workflow_user');
}
}
class User extends Model
{
public function works()
{
//return $this->belongsToMany(Role::class);
return $this->belongsToMany(Workflow1::class,'workflow_user');
}
}
workflow_user table
class WorkflowUser extends Model
{
protected $table = 'workflow_user';
protected $fillable = [
'workflow1_id','user_id','view'
];
protected $primaryKey = 'id';
public $timestamps = false;
}
To get the data from the workflow_user table I do this
$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);
When I make this request it does not give me the data of the workflow_user(workflow1_id,user_id,view) table.
If you have a model for the pivot table, you should have it extend the Pivot class and use it in the relationship's definition.
Also, you need to manually include the fields that are not the foreign ids in the query result.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
class User extends Model
{
public function works()
{
return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
workflow_user table
class WorkflowUser extends Pivot
{
protected $table = 'workflow_user';
protected $fillable = ['workflow_id', 'user_id', 'view'];
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
->works()
->orderBy('created_at', 'desc')
->paginate(10);
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();
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 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().