Answer the question
In order to leave comments, you need to log in
How to properly restructure the database for Laravel in order to correctly use the features of Eloquent?
Thanks to D''s advice and a correct kick, we managed to solve the previous hasMany problem.
But it turned out that the existing tables are not adapted for Laravel ... and they need to be somehow reformatted in order to link them. I would be grateful for practical advice-help...
What I have:
1) Reference table - countries (names of countries)
Structure:
id | country_name
2) User registration table - users
Structure
id| name | country_id
3) Table with holidays in countries - holidays
Structure
id | country_name (text) | date
I thought that I would link users and holidays, but that wasn't the case... in the holidays table, the id-list is just the serial number of the record, and the country name is stored in text...
Task 1: make the table structure holidays
id (holiday) | country_id | date
If I understand correctly, then I do a normal join to substitute the name of the country by its country_id.
I will receive approximately the following array of objects
id (holiday) | country_id | country_name (from countries) | date
In fact, while writing a question-request (an hour ago) I understood how to solve .... and it's a pity to delete ...
that's what I got ....
public function index(Holiday $holiday)
{
$holidays = $holiday -> getHolidays();
return view('bday.index', ['holidays' => $holidays]);
}
class Holiday extends Model
{
protected $table="holidays";
public function getHolidays() {
return $this->select(DB::raw("id,day,holiday,country_id,country_rus2,DATEDIFF(
CONCAT(
YEAR(CURDATE()),
'-', MONTH(day),
'-', DAY(day)
),
CURDATE()
) AS daysto"))
->havingRaw('daysto BETWEEN 0 AND 10')
->get();
}
public function name() {
return $this->hasOne('App\Country','rus_name','country_rus2');
}
public function users() {
return $this->hasMany('App\User','country_id','country_id');
}
}
Answer the question
In order to leave comments, you need to log in
If I were you, I would add a country_id foreign key to the holidays table
$table->integer('country_id')->unsigned()->index();
$table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question