I am trying to override the default names of the Laravel timestamps on a particular table, but it seems to be having no effect at all.
I have updated my model with the following:
/**
* The name of the "created_at" column.
*
* #var string
*/
const CREATED_AT = 'CreatedAt';
/**
* The name of the "updated_at" column.
*
* #var string
*/
const UPDATED_AT = 'UpdatedAt';
Updated the migration:
...
$table->integer( 'UpdatedBy' )->nullable();
$table->timestamps();
});
I run the migration and check the results in my database, and find that the fields have not changed:
...
| UpdatedBy | int(11) | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-----------------------+------------------+------+-----+-----------------------------------------+----------------+
Have I missed something maybe?
If you check Illuminate\Database\Schema\Blueprint you must be see that.
public function timestamps()
{
$this->timestamp('created_at')->nullable();
$this->timestamp('updated_at')->nullable();
}
If you wont to change your created_at, and updated_at columns then you can use
...
$table->integer( 'UpdatedBy' )->nullable();
$table->timestamp(CorrespondModel::CREATED_AT)->nullable();
$table->timestamp(CorrespondModel::UPDATED_AT)->nullable();
});
or directly create new names
...
$table->integer( 'UpdatedBy' )->nullable();
$table->timestamp('CreatedAt')->nullable();
$table->timestamp('UpdatedAt')->nullable();
});
Related
These are my Migrations
Type Migration
Schema::create('digital_types', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Content Migration
Schema::create('digital_products', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('product_type_id')->nullable();
$table->string('name');
$table->unsignedTinyInteger('status')->default(1);
$table->softDeletes();
$table->timestamps();
$table->foreign('product_type_id')->references('id')->on('digital_types')->nullOnDelete()->cascadeOnUpdate();
});
Models defined:
Type Model
class DigitalType extends Model
{
use HasFactory;
public function digitalContents() {
return $this->hasMany(DigitalProduct::class);
}
}
Content Model
class DigitalProduct extends Model
{
use HasFactory;
public function digitalContentType() {
return $this->belongsTo(DigitalType::class);
}
public function categories(){
return $this->belongsToMany(Category::class, 'digital_product_category');
}
}
But when I want to grab my Content with Type Relation by with method, It returns NULL.
My Controller
class DigitalProductController extends Controller
{
public function productsList(){
$products= DigitalProduct::with('digitalContentType')->get();
echo $products;
// return view('pages.digitalproducts', compact('products'));
}
}
and The data controller echo in browser is null (end of these two lines)
[{"id":1,"product_type_id":1,"name":"deserunt","description":"Id nam amet voluptatibus quia.","image_url":null,"content_url":null,"price":"3.00","discount":"7.00","status":1,"deleted_at":null,"created_at":"2021-12-29T13:47:41.000000Z","updated_at":"2021-12-29T13:47:41.000000Z","digital_content_type":null},
{"id":2,"product_type_id":3,"name":"aut","description":"Saepe ratione soluta aspernatur aspernatur debitis dolor.","image_url":null,"content_url":null,"price":"8.00","discount":"7.00","status":1,"deleted_at":null,"created_at":"2021-12-29T13:47:41.000000Z","updated_at":"2021-12-29T13:47:41.000000Z","digital_content_type":null},
And another thing that my Database populated with fake data, for both Content and Type
+----+------------+------------+------------+
| id | name | created_at | updated_at |
+----+------------+------------+------------+
| 1 | ebook | NULL | NULL |
| 2 | audio book | NULL | NULL |
| 3 | magazin | NULL | NULL |
| 4 | news paper | NULL | NULL |
+----+------------+------------+------------+
+----+-----------------+------------+----------------------------------------------------------------+-----------+-------------+-------+----------+--------+------------+---------------------+---------------------+
| id | product_type_id | name | description | image_url | content_url | price | discount | status | deleted_at | created_at | updated_at |
+----+-----------------+------------+----------------------------------------------------------------+-----------+-------------+-------+----------+--------+------------+---------------------+---------------------+
| 1 | 1 | deserunt | Id nam amet voluptatibus quia. | NULL | NULL | 3.00 | 7.00 | 1 | NULL | 2021-12-29 13:47:41 | 2021-12-29 13:47:41 |
| 2 | 3 | aut | Saepe ratione soluta aspernatur aspernatur debitis dolor. | NULL | NULL | 8.00 | 7.00 | 1 | NULL | 2021-12-29 13:47:41 | 2021-12-29 13:47:41 |
I think problem is that the foreign ID column in digital_products does not have name by Laravel standards.
If the column name is not by Laravel standard, you have to specify it in realtionship method:
public function digitalContentType() {
return $this->belongsTo(DigitalType::class, 'product_type_id');
}
I have two tables. 'weeks' and 'dates'
The weeks table holds an 'startDate' and an 'endDate' Both columns a foreignKeys to the dates columns. The dates table holds an primary key id and the date.
weeks
| IDweeks | startDate | endDate |
| 1 | 2 | 6 |
dates
| IDdates | date |
| 1 | 12-03-2018 |
| 2 | 13-03-2018 |
.....
When I query the weeks, I always get the keys for startDate and endDate. I would like to get the values from the dates tables instead.
I´ve already tried to eager load the values like this:
weeks Modal
class weeks extends Model
{
//....
public function startDate()
{
return $this->belongsTo('App\date', 'startDate', 'date');
}
public function endDate()
{
return $this->belongsTo('App\date', 'endDate', 'date');
}
//....
dates Modal
class date extends Model
{
protected $primaryKey = 'IDdates';
calling the 'with()' method
public function showWeeks() {
$weeks = weeks::with('startDate')->get();
return view('weeks')->with('weeks', $weeks);
}
using in the view
#foreach ($weeks as $week )
{{ $week->startDate->date }} // produces an error like: Trying to get property 'date' of non-object
{{ $week->startDate }} // works but returns only the keys instead of the value of dates table.
#endforeach
How can I load the results of the dates table when calling the weeks?
EDIT: edited a typo in the title
I have three tables as below:
------------------------------
| users | projects | clients |
|--------|-----------|-------- |
| id | id | id |
| name | client_id | name |
| | user_id | |
| | name | |
------------------------------
So basically the relationship is like:
User hasMany Project
Project belongsTo Client
My question is:
How can I get all clients of a user using eloquent?
Seems like I cannot user hasManyThrough method as there are no project_id in clients table.
So what I wish to achieve is :
foreach($users as $user)
foreach($user->clients as $client) //HOW TO SET UP THIS RELATION?
foreach($client->projects($user)->get() as $project)
$users = User::with('projects')->get();
// organize cleints' project and add for each user
foreach ($users as $user) {
// order projects by client_id
$projects = Collect($user->projects->toArray());
$clients = $projects->groupBy('client_id');
// keep projects data in 'projects' index
$temp = array();
foreach($clients as $client => $projects){
$temp[$client] = array('projects' => $projects);
}
// add clinets data for each user
$user['clients'] = $temp;
}
// output
foreach($users as $user)
foreach($user->clients as $client)
foreach($client['projects'] as $project)
echo 'user-'.$project['user_id'].', clinet-'.$project['client_id'].', project-'.$project['name'].'<br>';
Above code generated this output for me:
I am trying to access data from a database query which I think will need a join. I have users that can be apart of many groups. I am using a belongsToMany
relationship. My Models are like so
class User extends Model
{
protected $table = 'users';
protected $guarded = [];
public function group()
{
return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('user_id', 'group_id');
}
}
class Group extends Model
{
protected $table = 'user_groups';
protected $guarded = [];
use SoftDeletes;
public function user()
{
return $this->belongsToMany('App\User', 'users_user_groups')->withPivot('user_id', 'group_id');
}
}
When I run everything I need too, I might get data like the following.
users
+----+---------------+
| id | name |
+----+---------------+
| 1 | John Doe |
+----+---------------+
user_groups
+----+---------------+-----------------+
| id | name | description |
+----+---------------+-----------------+
| 1 | Group AA | Something |
+----+---------------+-----------------+
| 2 | Group BB | Something |
+----+---------------+-----------------+
users_user_groups
+----+---------------+-----------------+
| id | user_id | group_id |
+----+---------------+-----------------+
| 1 | 1 | 1 |
+----+---------------+-----------------+
| 2 | 1 | 2 |
+----+---------------+-----------------+
So I know user with the id 1 belongs to the user_groups with ids of 1 and 2. What I am trying to do is grab all the users within my database who
belong to a user_group with the name admin. So I am trying something like this
DB::table('users')->select('userName')
->join('user_groups', 'users_user_groups')
->where('name', '=', 'admin')->get();
This I know is all wrong, how can I get all users within a group when using belongsToMany and a pivot table?
Thanks
Eloquent uses relations, not the query builder.
You can achieve what you're aiming for by doing something like this:
$group = Group::where('name', 'admin')->first();
$users = $group->users; // Where users is the name of your relationship (At the moment you have user)
Under the hood that will do two SQL statements and map them together in eloquent objects, rather than a join. The statements will look something like this:
select * from user_groups where name = ? and deleted_at is not null limit 1
select * from users where id in (?, ?)
When you have an instance Group you execute the relationship by calling it as if it was a property. So after that $users will contain a collection of User instances, so you can just loop through them:
foreach ($users as $user) {
// Do something with $user
}
Here are my tables having a many-to-many relationship and group_user as the intermediate table.
| users | groups | group_user |
-------------------------------------------
| id | id | group_id |
| name | name | user_id |
| created_at| creator_id | created_at |
| updated_at| created_at | updated_at |
| | updated_at | |
groups.creator is the user id referenced from users table.
When I try to query the group table, it returns something like this.
[{"id":1,"name":"Akatsuki","creator":1,"created_at":"2015-10-13 12:22:20","updated_at":"2015-10-13 12:22:20"}]
What I want is when I query the groups table, it also returns the user data of the creator like hasOne relationships do.
In User Model
public function groups()
{
return $this->belongsToMany('App\Group')->withTimestamps();
}
In Group Model
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
After I query the groups, I just overwrite the group_creator column.
foreach($available as $data) {
$data['group_creator'] = User::find($data['group_creator']);
}
Now it returns
[{"id":1,"group_name":"Akatsuki","creator":{"id":1,"firstname":"John","lastname":"Doe","created_at":"2015-10-13 12:19:35","updated_at":"2015-10-13 14:14:41"},"created_at":"2015-10-13 12:22:20","updated_at":"2015-10-13 12:22:20"}]
Along with the user details.