Mysql Table Relations - Migrations LARAVEL - mysql

I am Creating my migrations with laravel, and I have this doubt:
I have these 2 tables:
Cars: ID || || BRAND_NAME || MODEL || YEAR
Brand: ID || NAME
So, if I would like to save Brand ID in my table Cars I use something like that:
$table->integer('brand_id')->unsigned();
$table->foreign('brand_id')->references('id')->on('brand');
All info it saved with a form and it works now. But if I would like to save BRAND_NAME instead of BRAND_ID in my Cars table. It's possible? How I can do this?

If you are specting something like:
$table->string('BRAND_NAME');
$table->foreign('BRAND_NAME')->references('NAME')->on('brand');
Then the answer is no unless your Name field in brand is indexed.
I beleave it is useless to store the name if you are using the brand id on Cars table, but I think the only way to do this is to make a query to get the brand name before you save the car model, something like:
$car = new Car;
$car->brand_id = 1;
$car->brand_name = Brand::find(1)->name;
$car->save();
You can keep your model as it is right now and use the hasOne relationship in Car model, so you can get all brand realted data to each car model. To do this you just need to add in you car model class a method like:
public function brand()
{
return $this->belongsTo('App\Car'); //<--- Put your car model path there
}
With that you can retrieve your Car model with all related brand data with something like:
$user = User::where("id", "=", 1)->with("brand")->first();
Check more info about relationships in https://www.laravel.com/docs/5.3/eloquent-relationships

Related

Count quantity of books by category, separate tables

I'm using Laravel 5 and I need to know the number of books by category, these data I will use on google charts.
I have the code below that I use to find out the number of users by sex. However, the data is in the same table.
$data = DB::table('books')
->select(
DB::raw('category_id as category'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
$array[] = ['Category', 'Number'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->category->name, $value->number];
}
$test = json_encode($array);
Using the same logic as above, how can I get the number of books by category?
I have the Books table:
ID | Name | ID_CATEGORY
1 Laravel 20
2 Java 20
Category table :
ID | Name
20 Programming
Could you help me in this situation?
You should just group by your ID_CATEGORY column instead of sex.
If you want to construct such array as before, you probably want the name of category. That would be easy if you used Eloquent. You would have $value->category->Name_Category available. If you want those preloaded instead of a query for every value, just add ->with('category') to the query and you'll have it.
If you are not using Eloquent, you should just load the category table separately, key it, and use $categories[$value->ID_CATEGORY]->Name_Category.
Other comments
DB::raw('sex as sex') is equivalent to sex.
++$key seems redundant, you could just push to the end by assigning to $array[].
Array with a header row is not very JSON. Typically you'd have key:value pairs all of the time.
You can construct the array using collection methods.
If you don't have good reasons for the opposite, you should stick to Laravel naming conventions.
I would probably not create an array myself, but do your example as something like this:
$stats = User::select('sex', DB::raw('count(*) as number'))
->groupBy('sex')
->get();
$stats->setVisible(['sex', 'number']);
return $stats;

Pivot table for single table in Laravel

I'm trying to add a multi-level categories in my website. where a category can have multiple child and also have multiple parent. It's look like many to many relationship in Laravel and I have to use a pivot table.
So that i create a table called categories and also a pivot table categories_reltionship like below. Now my question is how i will make this many to many relationship with this single table in Laravel.
categories table
==================
id title
=== ======
1 title_1
2 title_2
3 title_3
4 title_4
5 title_5
categories_relationship table
==================
parent_id child_id
========== ======
1 2
1 3
4 2
4 3
5 2
5 3
You can have methods like below on Category model :
//This will get you the list of categories
public function categories()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'child_id', 'id', 'id', 'parent_id'));
}
//This will get you the list of children
public function childs()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'parent_id', 'id', 'id', 'child_id'));
}
on CategoryRelation model :
class CategoryRelation extends Model
{
protected $table = 'categories_relationship';
}
I hope this will help you to solve your problem
Note : I suggest you to have 3 tables for many to many relationships,
in many to many relationship you should to have three tables. I hope that help you below example.
in our scenario as mentioned we have three tables with user , role and pivot names that each user can many roles and each role independent to many users.
user table have my_user_id(optional name) and other need column.
role table to have my_role_id (optional name) and other.
pivot table includes my_user_id , my_role_id.
in User model your codes should like below:
class User extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role', 'pivot', 'my_user_id', 'my_role_id');
}
}
in Role model your codes should like below:
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'pivot', 'my_role_id', 'my_user_id');
}
}
You can also refer to laravel official documentation:
many to many relationships

How can I compare 2 data in 1 table using where statement?

$users = User::where('id', 'parent_id')->get();
The id and the parent_id are in the same table. I want to get all of the data from the users table where the id and parent_id are equal. How can I do that in Laravel?
The issue you are facing is that you want to know how to check if the user has no referrals. You can do it like this:
Add referrer Relation in your user model.
public function referrer()
{
return $this->hasOne(self::class, 'parent_id');
}
You can then query it like this:
User::doesntHave('referrer')->get();
You should try this:
$users = User::whereColumn('id', 'parent_id')->get();

Laravel Eloquent ManyToMany getLatest

I built up a pivot table containing ids of tables I want to associate. When I have the id of a specific item, I now want to get the latest entry of this item saved in the pivot table. For example:
Table 1: Tickets
Table 2: Status
Table 3: Ticket_Status (Pivot)
If I add a new entry to the pivot table, I would have something like this:
Pivot
ticketId, statusId
1, 2
1, 3
2, 1
Now I want to receive the latest status in the pivot for Ticket Id 1 for example, so I expect to receive statusId 3 for ticket 1. But how do I do this in Laravel?
Creating the entries for the pivot table works:
public function attachDispatchStatus($id) {
$this->status()->attach($id);
$this->touch();
}
// set fields on the eloquent object and save to database
// raise event that the incident was created.
public function createDispatch($command) {
// Get BodyContent from POST Request
$this->dispatchReference = $command->dispatchReference;
$this->incidentReference = $command->incidentReference;
// Create new Dispatch
$dispatch = Dispatch::create(array(
'dispatch_reference' => $this->dispatchReference,
'incident_reference' => $this->incidentReference
));
$dispatchStatus = DispatchStatus::where('status', '=', 'processing')->first();
$dispatch->attachDispatchStatus($dispatchStatus->id);
return $this;
}
Why don't you use the updateExistingPivot($roleId, $attributes); available in Laravel 5 when editing your tickets ?
This will solve your problem and make your database lighter :)
Check Larvel Doc for some examples on pivot table.
If you don't want to make it like that (because you want to keep an historic of your input), I think you will have to add an dateTime field in your pivot table... Then, just order by date, and you will be fine.

Building an entity join LINQ query

I have the following table strutucture and am accessing them by using MySQL Entity Framework:
Table Users
- Id
- Name
Table Subscriptions
- Id
- Id_User
- Id_Course
Table Courses
- Id
- Name
What I would like and am having a hard time to do so is building a link query for all users that returns a list with each entry containing:
User Id;
User name;
Concat string separated by comma with all courses for the user or 'no courses' string if none.
This list should be filtered by a part of users name.
I've started to build the code but can't finish it:
var Model db = new Model();
var list = from user in db.Users
join ???
where user.Name.Contains(filter.Trim())
select new { Name = user.Name, Id = user.Id, ???}
Can anyone help me please ?
You should use navigation properties (like User.Subscriptions) for this. Depending on how you created the model they may already be there, else you first should add them.
var query = from u in db.Users
where user.Name.Contains(filter) // trim the filter value first
select new
{
u.Name,
u.Id,
Courses = u.Subscriptions.Select(s => s.Course.Name)
};
var result = query.AsEnumerable()
.Select(q => new
{
q.Name,
q.Id
Courses = string.Join(", ", q.Courses)
};
The reason for doing this in two phases is that string.Join can't directly be used in an EF LINQ expression (can't be turned into SQL) so it must be done in memory (i.e. after an AsEnumerable).
But still it may be efficient to do a projection first (the first part), otherwise too much data may be fetched from the database.