Here's my scenario:
I have a Event model and a Stage model, a event can have multiple stages and a stage could be assigned to multiple events. So Many-to-many. The thing is, a stage has a sort_order, and that sort_order could be different in each event. That's why I added the sort_order into the pivot table instead in, for example, the stage table.
table: events_stages
| event_id | stage_id | sort_order |
------------------------------------
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 1 | 5 | 3 |
The thing is when I'm going to relate the Stage with the events its in,
I'm doing something like in the StageController:
sending a post with events: [1,2,3] and sort_order: [1,1,2]
$relatedEvents = array();
foreach ($request->events as $key => $event)
{
$relatedEvents[] = array(
'event_id' => $relatedEventId,
'sort_order' => $request->sort_order[$key]
);
}
$stage->events()->sync(
$relatedEvents
);
but rely simply in the order of the post, doesn't seem like a really good idea.
Does anyone have a nicer solution?
Thanks!
Sometimes is better to create another model (and use it as a pivot) rather than use pivot table itself. You have more control. I'm not sure what exactly you want to achieve.
Related
I'm trying to make some query with Eloquent but cannot get the result I really want. Using Laravel 6.
I have the next tables:
Table Users:
id | user
============
1 | Andy
Table Colors:
id | color
============
1 | red
2 | blue
3 | white
4 | green
5 | black
Table user_colors:
id | user_id | color_id
==========================
1 | 1 | 1
1 | 1 | 4
What I want is something to get all the colors, but mark as active the ones in the pivot. Something like this:
id | color | active
====================
1 | red | 1
2 | blue
3 | white
4 | green | 1
5 | black
Any idea?
This should return a collection of Color objects with the one's associated with the given user given a property of active set to true
$user_colors = User::find(1)->colors;
$colors = Colors::all()->transform(function ($color) use ($user_colors) {
if ($user_colors->contain($color)) {
$color->active = true;
}
return $color;
});
Whilst this should achieve the result you need, without knowing the context in which you want to use it, it may be inefficient.
There are several ways to achieve this task. One of them could be to use appends in models.
Appends are attributes that you can dynamically add to your model class.
E.g. you can edit your Color model like this:
class Color extends Model {
// Your code...
protected $appends = ['active'];
public function getActiveAttribute() {
$is_active = UserColor::whereColorId($this->id)->first();
if (!is_null($is_active)) return true; // Or 1, up to you
return false; // Or 0, up to you
}
}
If you use this method, you can access to $color->active attribute.
Note that this is only one of the different methods that you can use to do this task.
Reference: Laravel Appends Documentation
I have a multiple select:
Form::select('color', array('1' => 'Red', '2' => 'Blue', '3' => 'Green', ... ), null, array('multiple'));
How can I insert these values into a table on separate rows, like this:
id | user_id | color
----------------------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 1 | 4
5 | 2 | 1
6 | 2 | 3
In the above example, user with an id of 1 selected 4 different values in the select and each was inserted on a separate row.
I have this working in this way:
foreach (Input::get('tags') as $key => $value)
{
$user_color = new UserColor;
$user_color->user_id = $user->id;
$user_color->color = $key;
$user_color->save();
}
Is there a better way of doing this? It seems odd using a foreach loop when it feels like Laravel should have some sort of built-in method of inserting multiple values on multiple rows.
As Laravel doc provided,
You may also use the sync method to attach related models. The sync
method accepts an array of IDs to place on the pivot table. After this
operation is complete, only the IDs in the array will be on the
intermediate table for the model:
In this case,
$colors = Input::get('tags');
$user->colors()->sync($colors);
Please make sure to set relation in your User model :
public function colors()
{
return $this->belongsToMany('Color');
}
You can also use attach method when you parameter is not array. To more clear, Here is difference between attach and sync.
I'm wondering if its possible to set the operator when using a HasMany relationship in Laravel 4.2.
I'm working with a users table and an email log table. The log table has a userID stored in serialised format (as there may be more than one userID stored within the log).
Users table
+---------+
| user_ID |
+---------+
| 1 |
| 2 |
+---------+
emailLog Table
+----+--------------------+
| ID | user_ID |
+----+--------------------+
| 1 | a:1:{i:0;s:1:"2";} |
| 2 | a:1:{i:0;s:1:"1";} |
+----+--------------------+
Am I able to use a hasMany relation with a 'Like' operator rather than an equals operator to return the correct email log ID? Would the statement be written something like the below?
return $this->hasMany('emailLog', 'user_ID', '%user_ID%', 'LIKE');
The proper way to return join table with a where clause would be:
return $this->hasMany('emailLog','user_id')->where('user_id', 'LIKE', '%user_id%');
I found a way to do something similar
class User extends Model
{
public function emailLogs()
{
// old code
// return $this->hasMany(EmailLogs::class, 'user_ID');
// Replace HasMany by like query
return EmailLogs::where('user_ID', 'LIKE', "%{$this->user_ID}%");
}
}
I have the following three tables but I don't know how to build a relation between the category and the other data type, in this case 'Page':
posts:
post_id | title | slug
1 | Test | test
2 | Another test | another test
catgory_map:
id | category_id | referrer_id | category_map_type
1 | 2 | 1 | Post
2 | 3 | 2 | Post
3 | 2 | 9 | Page
category
id | name
1 | Laravel
2 | Zend2
3 | Phalcon
So whenever I read a Category I like to be able to do something like this
foreach($category->destinations) ...
I have tried until now with hasManyThrough but it didn't work.
What you have is a many-to-many relation with some additional filtering on the relationship (for the category_map_type). Try this:
Post model
public function categories(){
return $this->belongsToMany('Category', 'category_map', 'referrer_id')
->where('category_map_type', 'Post');
}
Category model
public function posts(){
return $this->belongsToMany('Post', 'category_map', 'category_id', 'referrer_id')
->where('category_map_type', 'Post');
}
Usage
$category = Category::find(1);
foreach($category->posts as $post){
// ...
}
(And the same goes for Post)
You might also want to look into polymorphic many-to-many relations
I have two tables - contacts and visits:
Contacts Table
id | name
----- | -------
1 | Joe
2 | Sally
Visits Table
id | contact_id | pathname | referrer
----- | ------- | ------- | -------
1 | 1 | about | google
2 | 1 | pricing | null
3 | 1 | signup | null
4 | 2 | about | null
5 | 2 | signup | null
Using eloquent, I would like to retrieve all contacts that have a both a pathname = 'signup' AND a referrer = 'google'.
What I've got so far is:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->orWhereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
Which properly retrieves all contacts that have visited either the pricing OR signup page.
However, this example would also retrieve Sally (from the example table above), since she visited signup, but was not referred by google. I need a way to only retrieve Joe, who was both referred by google and visited pricing.
Any ideas? Thanks in advance!
You can use:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->whereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
A refined version of the code above:
Contact::whereHas('visits', function($query) {
$query->where('pathname','signup')->where('referrer','google');
})->get();
Several noteworthy points:
You can chain where() clauses within a closure.
The default operator for a where clause is =, so you can omit it.
Use multiple whereHas() clauses, when accessing multiple related models.