I have a make table and post table. Make table saves make names as make_code and make_name.
Post table has a column make. While saving a post, it will save make in make_code.
While displaying in blade, I want it to display as make_name. How can I do it?
Currently {{$post->make}} gives me make_code. I need it to show make_name.
I think its a one-to-one relationship that's needed. I tried putting it in model but did not work. How can I achieve it?
MAKE MODEL
class Make extends Model
{
public function make()
{
return $this->belongsTo(App\Post::class);
}
}
POST MODEL:
class Post extends Model
{
protected $table = 'posts';
}
Update
As Tim Lewis noticed:
the relationships can't be named make, as that's a conflict.
Assuming that the your relationship work like this:
a Make has many Post
a Post belongs to a Make object.
| Note: Correct me if I'm wrong.
So, if this is correct, you should define your relationships like this:
Post.php
public function make_rel()
{
return $this->belongsTo(Make::class, 'make', 'make_code');
}
Make.php
public function posts()
{
return $this->hasMany(Post::class, 'make', 'make_code');
}
Check the One-to-Many and One-to-Many (Inverse) relationship sections of the documentation.
So, you could do in your controller (or wherever you want):
$post = Post::find(1);
dd($post->make_rel->make_name); // 'Harley Davidson'
Additionally, you could create a computed property as a shorcout to access this related property in your Post model:
Post.php
// ...
public function getMakeNameAttribute()
{
return $this->make_rel->make_name;
}
Now, you can access it like this:
$post = Post::find(1);
dd($post->make_name); // 'Harley Davidson'
Suggestion
As a suggestion, I strongly advice you to change your foreign key column from make to make_id (in your 'posts' table) to avoid conflicts. Also, you could relate the post to the make primmary key instead of a custom key given the fact that this link is almost invisible and it is handled by Laravel. This would speed up the execution of the query because primmary id's are indexed by default.
Related
I'm currently struggling with retrieving data towards a parent model. I'll drop my database, classes, and things I've tried before.
I have 4 tables: sales_orders, products, work_orders, and product_sales_order (pivot table between sales_orders and products).
SalesOrder.php
class SalesOrder extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)
->using(ProductSalesOrder::class)
->withPivot(['qty', 'price']);
}
}
ProductSalesOrder.php
class ProductSalesOrder extends Pivot
{
public function work_orders()
{
return $this->hasMany(WorkOrder::class);
}
public function getSubTotalAttribute()
{
return $this->qty* $this->price;
}
}
WorkOrder.php
class WorkOrder extends Model
{
public function product_sales_order()
{
return $this->belongsTo(ProductSalesOrder::class);
}
public function sales_order()
{
return $this->hasManyThrough(
ProductSalesOrder::class,
SalesOrder::class
);
}
}
So, what I want to retrieve sales order data from work order since both tables don't have direct relationship and have to go through pivot table and that is product sales order. I've tried hasOneThrough and hasManyThrough but it cast an error unknown column. I understand that error and not possible to use that eloquent function.
Is it possible to retrieve that sales order data using eloquent function from WorkOrder.php ?
You cannot achieve what you want using hasOneThrough as it goes from a table that has no ID related to the intermediate model.
In your example you are doing "the inverse" of hasOneThrough, as you are going from a model that has the ID of the intermediate model in itself, and the intermediate model has the ID of your final model. The documentation shows clearly that hasOneThrough is used exactly for the inverse.
So you still should be able to fix this, and use a normal relation as you have the sales_orders_id in your model SuratPerintahKerja, so you can use a normal relation like belongsTo to get just one SalesOrder and define it like this:
public function salesOrder()
{
return $this->belongsTo(SalesOrder::class, 'sale_orders_id');
}
If you want to get many SalesOrders (if that makes sense for your logic), then you should just run a simple query like:
public function salesOrders()
{
return $this->query()
->where('sale_orders_id', $this->sale_orders_id)
->get();
}
Have in mind that:
I have renamed your method from sales_order to salesOrder (follow camel case as that is the Laravel standard...).
I have renamed your method from sales_order to salesOrders for the second code as it will return more than 1, hence a collection, but the first one just works with one model at a time.
I see you use sale_orders_id, but it should be sales_order_id, have that in mind, because any relation will try to use sales_order_id instead of sale_orders_id, again, stick to the standards... (this is why the first code needs more parameters instead of just the model).
All pivot tables would still need to have id as primary and auto incremental, instead of having the id of each related model as primary... Because in SuratPerintahKerja you want to reference the pivot table ProdukSalesOrder but it has to use both produks_id (should have been produk_id singular) and sale_orders_id (should have been sales_order_id). So if you were able to use something like produk_sales_order_id, you could be able to have better references for relations.
You can see that I am using $this->query(), I am just doing this to only return a new query and not use anything it has as filters on itself. I you still want to use current filters (like where and stuff), remove ->query() and directly use the first where. If you also want to add ->where('produks_id', $this->produks_id) that is valid and doesn't matter the order. But if you do so, I am not sure if you would get just one result, so ->get() makes no sense, it should be ->first() and also the method's name should be salesOrder.
Sorry for this 6 tip/step, but super personal recommendation, always write code in English and do not write both languages at the same time like produks and sales orders, stick to one language, preferrably English as everyone will understand it out of the box. I had to translate some things so I can understand what is the purpose of each table.
If you have any questions or some of my code does not work, please tell me in the comments of this answer so I can help you work it out.
Edit:
After you have followed my steps and changed everything to English and modified the database, this is my new code:
First, edit ProductSalesOrder and add this method:
public function sales_order()
{
return $this->belongsTo(SalesOrder::class);
}
This will allow us to use relations of relations.
Then, have WorkOrder as my code:
public function sales_order()
{
return $this->query()->with('product_sales_order.sales_order')->first();
}
first should get you a ProductSalesOrder, but then you can access ->sales_order and that will be a model.
Remember that if any of this does not work, change all the names to camelCase instead of kebab_case.
In my database I have to save people and the data of people that have a relationship with the first. For example: father, mother, son, daughter, etc
Then the design of the database, I did it in the following way Is a relation many-to-many because, a person have many people related to it.
But I'm not sure if is ok..
class Person extends Model
{
protected $fillable = [
'name',
'surname',
'profile_picture'
.....
];
public function relationships()
{
return $this -> belongsToMany(Person::class);
}
}
When I create the relation I create a thirth migration table call person_person to save the ids and a description (father, mother, son, daughter)
it's ok describe the relationship this way?
public function relationships()
{
return $this -> belongsToMany(Person::class);
}
What should I add to complete successful this relationship?
You'll need to define the table, primary and foreign key, as Laravel likely can't determine this (it'll try, but it probably won't succeed). Something like:
public function relationships(){
return $this->belongsToMany(Person::class, "person_person", "id_person", "id_person_related")
->withPivot(["parentesco"]);
}
or similar. Table name is a bit awkward, consider something else, like 'relationships' or something that conveys more meaning.
See https://laravel.com/docs/5.8/eloquent-relationships#many-to-many for details on how to define additional parameters for belongsToMany()
Laravel provide a nice convention for manyToMany relationship for two different tables but this convention does not work when we need manyToMany relationship in the same table.
solution steps:
create a pivot table and give it a meaningful name like relatives(person_person is not suitable)and create tow columns in this table persion_id and relative_persion_id.
with classname, pass other three arguments as the Table name (relatives), persion_id and relative_persion_id.
this link has perfect solutuion https://laracasts.com/series/laravel-6-from-scratch/episodes/58
public function relationships() { return $this->belongsToMany(Person::class,'relatives','persion_id','relative_persion_id'); }
I have a newsletter and block model that has a many to many relation. When I attach a block to a newsletter I want the id of the row that was insterted in the pivot table.
This is what I tried but results in "null"
$newsletter = Newsletter::findOrFail($newsletterId);
$newsletterBlock = $newsletter->blocks()->attach($blockId);
dd($newsletterBlock);
Although this question is old, however nobody gave the right answer. If you are in a situation that your pivot table has a primary key.
Using withPivot method is useful when you want get the id when you load the related model. However when you attach something you can not get the pivot_id;
In these situations best thing to do is to use a model that is connected to the pivot table, then only thing you need to do is inserting into pivot table using its model instead of attaching two models together.
in this example, first create a model called BlockNewsLetter if it is necessary fill the $table and $fillable attributes of the model and then you are good to go.
$newsletter = Newsletter::findOrFail($newsletterId);
$blockNewsLetterPivot = BlockNewsLetter::updateOrCreate([
'block_id' => $block_id ,
'newsLetter_id' => $newsletter->id
]);
$inserted_pivot_id = $blockNewsLetterPivot->id;
Try this, haven't test it but this should work:
/** Newsletter.php */
public function blocks()
{
return $this->belongsToMany('App\Block')
->withPivot('id');
}
Then in your controller:
$newsletter = Newsletter::findOrFail($newsletterId);
$newsletter->blocks()->attach($blockId);
// then you could:
foreach($newsletter->blocks as $block)
{
dd($block->pivot->id);
}
Check this section of the docs.
I have gotten a model called User. in this model i have a function called UserActivity where i return this:
return $this->hasMany('App\UserActivity', 'userid');
After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:
public function Activity() {
return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}
And in my view i want to use this like this:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());
But then i get an error saying this:
Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)
I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:
Users: pk: id
user_activities: pk: userid, activityid
activities: pk: id
Thank you in advance!
You can try using eager loading.
So something like:
$activiteiten = \App\User::with('UserActivity.Activity')->find(Auth::user()->id);
dd($activiteiten->UserActivity->Activity);
Edit: So then you can do something like this:
foreach($activiteiten->UserActivity as $user_activity) {
foreach($user_activity->Activity as $activity) {
print_r($activity);
}
}
Shows how you can loop through the relationships.
The Activity function should be in the User model. So then you can call it this way:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->Activity); //gives you a collection of activities
However, you need belongsToMany function rather than hasManyThrough since the relationship between users and activities is many-to-many.
This mean you cut down going through the Intermediate model. You can check the doc on belongsToMany to understand what to do better.
A side note: Why are your functions name starting with capital letter?
Also using hasMany relations should affect the function name as well, so that 'activity' becomes 'activities' (just to keep the functionality and interpretation in sync).
Update:
//User model
public function activities() {
return $this->belongsToMany('App\Activity', 'user_activity', 'userid', 'activityid');
}
This uses the 'user_activity' table, to find the relationship between users and activities, so that you may now access by User::first()->activities for example.
I am trying to figure out a relationship but I can't seem to solve the issue.
So what my script does first is checking if there is a valid session where status = 0.
Then I want to check if there is a valid trial where status = 0 ->first() associated with that session. And if so, I want to grab all the relevant data related by trial_id.
I understand what logic is required. However, I am wondering if there is a method to do this with as little commands as possible using Eloquent relationships.
Specifically, once i have the $session object. How can I filter the trials, in order to get the appropriate stimuli_tracker data?
The important components to the relationships for the table is as follows:
Sessions
id (has one to many relationship to trials(sessions_id)
user_id (foreign key)
status
Trials
id (one to many relationship with stimuli_tracker)
sessions_id (foreign key)
status
Stimuli_Tracker
trials_id (foreign key)
stimulus
stimulus_type
Sessions Model
class Sessions extends Model
{
protected $table = 'sessions';
public function stimuliTracker()
{
return $this->hasManyThrough('App\StimuliTracker', 'App\Trials', 'sessions_id','trials_id');
}
}
Trials Model:
class Trials extends Model
{
public function stimuli()
{
return $this->hasMany(App\StimuliTracker);
}
}
EDIT
I have tried in artisan tinker to
$object = \App\Session::where(arg);
then I tried to
$object->stimulus
but didn't work. I tried a few other fields but I only received null. Maybe I'm not getting how to grab the content properly
$object->stimulus is an undefined attribute based on what you've shown in your code.
To access the stimulus information for your session, you have to use the name of the relationship, which in this case is:
$object->stimuliTracker
The thing is that this will return an Eloquent Collection because it is a hasManyThrough relationship (which is a hasMany of a hasMany).
I'm assuming that the 'stimulus' attribute belongs to the StimuliTracker class. If this is the case, then you will need to loop through your StimuliTracker Collection to extract it:
foreach ( $object->stimuliTracker as $record )
{
$stimulus = $record->stimulus;
// do something with $stimulus
}
EDIT (Added):
If you are just looking for an array of the values in the 'stimulus' attribute, you can get that with the lists() method:
$stimulus_values = $object->stimuliTracker->lists('stimulus');