Let me first explain the relations of my table, and then I will explain what I cannot do.
So, I have an entity called "Company" it has many "Incomes" which has many "IncomeUnitSale" which has one "IncomeUnitSaleUnitPrice"
Company 1->* Income 1->* IncomeUnitSale 1->1 IncomeUnitSaleUnitPrice
Models:
Company Model
public function Income(){
return $this->hasMany('App\Income');
}
Income Model (table has "company_id")
public function Company(){
return $this->belongsTo('App\Company');
}
public function IncomeUnitSale(){
return $this->hasMany('App\IncomeUnitSale');
}
IncomeUnitSale Model (table has "income_id")
public function Income(){
return $this->belongsTo('App\Income');
}
public function IncomeUnitSaleUnitPrice(){
return $this->hasOne('App\IncomeUnitSaleUnitPrice');
}
IncomeUnitSaleUnitPrice (table has "income_unit_sale_id")
public function IncomeUnitSale(){
return $this->belongsTo('App\IncomeUnitSale');
}
What I am trying to do is the following:
$company = Company::where("id","=",1)->first();
$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice
But It says its null, it works till $company->Income->IncomeUnitSale but after that doest't show any relation.
Can somebody please tell me what I am doing wrong?
Thank you!
hasMany relationships will always return an Eloquent Collection object. If there are no related records, it will just be an empty Collection. hasOne and belongsTo relationships will always return either the related Model, or null if there is no related model.
Because some of your relationships are hasMany, you have to iterate the returned Collection to be able to go further. So, instead of $company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice, you have to:
foreach($company->Income as $income) {
foreach($income->IncomeUnitSale as $sale) {
echo $sale->IncomeUnitSaleUnitPrice->price;
}
}
Related
My table has many foreign key for example prefecture_id, gender_id and status_id.
And I made model for those table.
So I want to define multiple belongsTo method like following for get all data with query builder..
But In fact belongsTo can't use like this.
public function foreign(){
return $this->belongsTo([
'App/Prefecture',
'App/Gender',
'App/Status',
]
}
And if the only way is defining multiple method for belongs to.
How do I get all belongstos data in querybuilder.
Please give me advice.
As far as I am aware, there's not a way to get multiple belongsTo from a single method. What you have to do is make one method for each relationship and when you want to load the relationships you can do the following.
Model
public function prefecture()
{
return $this->belongsTo(\App\Prefecture::class);
}
public function gender()
{
return $this->belongsTo(\App\Gender::class);
}
public function status()
{
return $this->belongsTo(\App\Status::class);
}
Query
// This will get your model with all of the belongs to relationships.
$results = Model::query()->with(['prefecture', 'gender', 'status'])->get();
I have a table called "categories" and there is a 3 table needed the id of categories
the 3 tables needed a categories id is "activies", "stories", "news" i really want to know how to fix this issue the stories and news table is running well im using php tinker to see if the relationship is running and the table activities it give me a null value, inside the activities table i`d input same category_id in the table of activities it gives always a null value given in php tinker
Models
Category.php
public function stories()
{
return $this->hasMany(Story::class);
}
public function news()
{
return $this->hasMany(Newy::class);
}
public function activites()
{
return $this->hasMany(Activity::class);
}
Activity.php
public function category()
{
return $this->belongsToMany(Category::class, 'category_id');
}
If you are using hasMany in your Category Model, the opposite relationship in your Activity model should be belongsTo() and not belongsToMany()
public function category()
{
return $this->belongsTo(Category::class);
}
You can read more in the documentation here
I have a polymorphic relationship using a pivot table with some simple columns.
The pivot table has created_at and updated_at. Is there anyway I can set Accessors on those, so I can have them formatted in the collection without looping through it?
public function organization()
{
return $this->morphedByMany('App\Organization', 'relationship')->withPivot('relationship_level')->withTimestamps();
}
public function regions()
{
return $this->morphedByMany('App\Region', 'relationship')->withPivot('relationship_level')->withTimestamps();
}
public function groups()
{
return $this->morphedByMany('App\Group', 'relationship')->withPivot('relationship_level')->withTimestamps();
}
This is the code. I want when I try to access ->pivot->created_at to get it formatted in human way.
You can write an accessor on your polymorhic model, i.e.:
public function getFooAttribute()
{
return $this->pivot ? $this->pivot->created_at->format('Y-m-d') : 'pivot not loaded';
}
And access with $model->foo.
Remember that $model should be loaded by its Owner model so you have the pivot loaded, i.e.:
Region::with('polymorphic_models')->find($id);
And you have to define ->withPivot('relationship_level')->withTimestamps(); on both sides of the relationship.
I am trying to count related tables via model but can't successful.
I have a categories, questions and answers table.
I can count questions related to a category but can't count answers from related categories. U can think its a forum system.
Category Model
public function questions(){
return $this->hasMany('App\Question','category_id','id');
}
Question Model
public function answer()
{
return $this->hasMany('App\Answer');
}
public function category()
{
return $this->belongsTo('App\Category','category_id','id');
}
Answer model
public function question()
{
return $this->belongsTo('App\Question','question_id','id');
}
I can count questions for a related category view Category model like below
public function questioncount(){
return $this->questions()->where('status',1)->count();
}
Tried below for counting answers but no luck;
public function answercount()
{
return $this->questions()
->leftJoin('answers','answers.question_id','=','questions.id')
->count();
}
You might try Has Many Through relationship.
So let's define a Has Many Through relationship in Category model:
class Category
{
public function answers()
{
return $this->hasManyThrough(Answer::class, Question::class);
}
}
Then of course you can get the answers count like this:
$question->answers()->count();
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:
$answers = App\Question::withCount('answers')->get();
i have two tables
**students :**
id
family_id
name
**family :**
id
father_name
father_civil_id
contact_no
both tables are connected using family_id, i want to get how many Brothers/Sisters each students have(with name of sibling) using eloquent.
can you please help me, with controller/model/view.
Let's say you have a Student and Family model. Then you have several ways to do it.
Here are the two easiest ones I can guess with the information you provided.
Without relationship
Controller
Student::where('family_id', $family_id)->get();
HasMany relationship
Family model
class Family extends Model
{
// Since Laravel will expect your table to be 'families'
protected $table = 'family';
public function students()
{
return $this->hasMany(Student::class);
}
}
Controller
$family = Family::with('students')->inRandomOrder()->first();
$siblings = $family->students;
In Students Model:
public function family() {
return $this->belongsTo('App\Models\Family');
}
public function getSiblings() {
return $this->family->students;
}
So you can call it by your students:
$student->getSiblings();