How to select common date from three tables in laravel? - eloquent

I have these three tables in my database and I want to select the common date from three tables to calculate the profit of every day , profit of every month, and profit of every year
this is my tables :
Schema::create('expenses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->float('amount');
$table->string('month');
$table->string('year');
$table->string('date');
});
Schema::create('service_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('client_id')->unsigned();
$table->double('total_price', 8, 2)->nullable();
$table->string('month');
$table->string('year');
$table->date('date');
$table
->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('client_id')->unsigned();
$table->double('total_price', 8, 2)->nullable();
$table->string('month');
$table->string('year');
$table->date('date');
$table
->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});

I think your problem can be solved by UNIONS
UNION used to combine the result of two or more tables
SELECT date FROM expenses
UNION ALL
SELECT date FROM service_orders
UNION ALL
SELECT date FROM orders
To use it in Laravel you can check documentation below:
https://laravel.com/docs/5.8/queries#unions

Related

Single model using many-to-many relationship with several other models

I want to have a single table containing information about people (name, phone, email) called contacts that can then be associated with several other tables (clients, properties, jobs). However, I have no clue how to approach this through Eloquent. I considered having 2 additional fields in the contacts table, an entity_id and an entity_type to identify the associated records in the other tables, but I am hoping there is a cleaner, more Laravel way to accomplish this.
create_contacts_table.php
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('phone')->nullable();
$table->string('email')->nullable();
$table->timestamps();
});
create_clients_table.php
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address_1');
$table->string('address_2')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->integer('zip_code')->nullable();
$table->timestamps();
});
create_properties_table.php
Schema::create('properties', function (Blueprint $table) {
$table->id();
$table->string('address_1');
$table->string('address_2')->nullable();
$table->string('city');
$table->string('state');
$table->integer('zip_code');
$table->timestamps();
});

Laravel eloquent limit query

I have 3 tables TAble, TableB and TableC.
each one with 1 milion registers.
And i have the Laravel eloquent query.
$list= TableA::with([
'TableB',
'TableC'
])
->whereIn('field1',['A','B','C'])
->where('created_at','>=','2018-01-01') ->orderBy('fieldC', 'ASC')->orderBy('created_at', 'ASC')
->get()
->take(50) ;
TableA have TableB and TableC mapping this way.
public function TableB(){
return $this->belongsTo('TableB', 'fk_id', 'id');
}
public function TableC(){
return $this->hasMany('TableC');
}
How can i execute this query limiting number of registes in "TableB" and "TableC".
if i use take() it only limits the final result.
What do you want to do?
If you want to process data in chunks use
->chunk(50, function ($data) use ($variable) {
//process
});
If you want display data in tables with pages use paginate.

how to select particular column from relationship collection table in laravel mongodb jessenger

I have 3 columns in my database. 2 columns is connected with one column by using a hybrid relationship.
here is my query.
$data=Client::with('product','department')->select(['product.product_name','product.product_description']);
how to select row from another table?
in your product or department relation method do the selection with all the forging keys if you have any other relation for product for later use is you want them like
public function product()
{
return $this->hasMany(department::class)->select(['id', 'another_relation_to_product_id', 'product_name', 'product_description']);
}
You can do it this way
$data = Client::with(['product:id,product_name,product_description','department'])->get();
see docs https://laravel.com/docs/5.7/eloquent-relationships#constraining-eager-loads in Eager Loading Specific Columns section. Or you can do it
App\User::with([
'product' => function ($query) {
$query->select('id', 'product_name', 'product_description');
},
'department'
])->get();

Selecting all records created current year with Eloquent

I need to select records created at current year, with Eloquent
So far, this is the code I'm using. How can I filter the results to retrieve only the ones created in the current year?
public function vacationsbalance($typeId) {
// Get vacataions balance for existing employee.
$vacationsBalance = $this->vacations()->where('vacation_type_id', '=', $typeId)->sum('days_num');
return $vacationsBalance;
}
Assuming you have timestamps in your table (that is, you have a created_at column with the record's creation date), you can use:
public function vacationsbalance($typeId) {
// Get vacations balance for existing employee and for the current year.
return $this->vacations()
->where('vacation_type_id', '=', $typeId)
->whereRaw('year(`created_at`) = ?', array(date('Y')))
->sum('days_num');
}
Check Eloquent's documentation and look for whereRaw.

Laravel 5 hasManyThrough Pivot Table

I am trying to create a relationship to access a table called comments through a model called grade, loaded through the students in the grade
Both the Grade and Student models belongToMany of the other
From my understanding, it is not possible to access a hasManyThrough relationship that requires a pivot table (comments do not have a Grade identifier, only a student identifier)
class Grade extends Model{
public function comments(){
return $this->hasManyThrough("App\Comment","App\Student");
}
}
I have these functions I found for Laravel 4 # HasManyThrough with one-to-many relationship but it gives me the error Class 'App\Illuminate\Database\Eloquent\Relations\HasMany' not found
I don't have a good understanding on Namespaces, and can't work out what I should be doing in it's place for Laravel 5.
public function getCommentsAttribute()
{
if ( ! array_key_exists('comments', $this->relations)) $this->loadComments();
return $this->getRelation('comments');
}
protected function loadComments()
{
$comments = Comment::join('grade_student', 'comments.student_id', '=', 'grade_student.student_id')
->where('grade_student.grade_id', $this->getKey())
->distinct()
->get(['comments.*','grade_id']);
$hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Translation::query(), $this, 'grade_id', 'id');
$hasMany->matchMany(array($this), $comments, 'comments');
return $this;
}
More Info
Comment Table
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('student_id')->unsigned();
$table->integer('domain_id')->unsigned();
$table->integer('teacher_id')->unsigned();
$table->text('comment');
$table->foreign('student_id')->references('id')->on('students') ->onDelete('cascade');
$table->foreign('domain_id') ->references('id')->on('domains')->onDelete('cascade');
$table->foreign('teacher_id')->references('id')->on('teachers')->onDelete('cascade');
});
My Students Table
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('unique_identifier');
$table->string('first_name');
$table->string('last_name');
$table->enum('gender',array('m','f'));
});
My Grades Table
Schema::create('grades', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name',20);
$table->integer('school_id')->unsigned();
$table->integer('level_id')->unsigned();
$table->foreign('school_id')->references('id')->on('schools')->onDelete('cascade');
$table->foreign('level_id')->references('id')->on('classes_levels')->onDelete('cascade');
});
My Pivot Table
Schema::create('grade_student', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->timestamps();
$table->integer('grade_id')->unsigned();
$table->integer('student_id')->unsigned();
$table->integer('school_id')->unsigned();
$table->integer('year');
$table->foreign('grade_id')->references('id')->on('grades')->onDelete('cascade');
$table->foreign('student_id') ->references('id')->on('students')->onDelete('cascade');
$table->foreign('school_id')->references('id')->on('schools') ->onDelete('cascade');
});
Take a look at here.
At the moment Laravel 5.3 doesn't support hasManyThrough using pivot table. Just use an alternative ways.
As an alternative way:
Just consider these models and their relations:
A <=> B with pivot table A_B
B <=> C with pivot table B_C
Now you can create a pivot VIEW call A_C:
SELECT A_id, C_id FROM A_B
INNER JOIN B_C on A_B.B_id = B_C.B_id
GROUP BY A_id, C_id
I think you can guess my trick.
Yes, forget about hasManyThrough.
Now you can use A.belongsToMany(C).