Laravel Eloquent relationships - hasOne? - laravel

I have a question table which has a type_id column. The value defined here relates to the QuestionTypes model.
Question Table:
--------------------------
| id | title | type_id |
--------------------------
| 1 | apple? | 2 |
| 3 | banana? | 2 |
| 4 | kiwi? | 2 |
| 5 | pear? | 3 |
--------------------------
QuestionTypes
----------------
| id | title |
----------------
| 1 | multi |
| 2 | single |
| 3 | free |
----------------
In the Questions Model I have:
public function type()
{
return $this->hasOne(QuestionType::class);
}
I would like to print the title from questiontypes table but when I try to output in the view using $question->type->title I get:
Column not found: 1054 Unknown column 'x__questiontypes.questions_id' in 'where clause'
(SQL: select * from `x__questiontypes` where `x__questiontypes`.`questions_id` = 2 and `x__questiontypes`.`questions_id` is not null limit 1
Have I mixed up the relationships?

Solution via Attaching a hasOne model to another Laravel/Eloquent model without specifying id
Updated to Questions model:
public function type()
{
return $this->belongsTo(QuestionType::class, 'type_id');
}
Added to QuestionType model:
public function questions()
{
return $this->hasMany(Question::class, 'type_id');
}

Related

How to write Eloquent relation for one table to another table two columns?

I am trying to join two columns with a table.
Here is my table structure for tasks table
| id | assigned_by | assigned_to |
| :--- | :---: | ---: |
| 1 | 1 | 2 |
| 2 | 1 | 3 |
Here is the table structure of users table.
| id | name | email |
| :--- | :---: | ---: |
| 1 |varun | me#gmail.com |
| 2 |mark | mark#gmail.com|
I tried below code in Task Class it didn't work
public function user()
{
return $this->belongsTo(User::class);
}
Eloquent will automatically determine the proper foreign key column on the User model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for your example, Eloquent will assume the foreign key on the User model is user_id.
However, your foreign_key is assigned_by and assigned_to, so you need to specify the foreign_key:
public function assignedUser()
{
return $this->belongsTo(User::class, 'assigned_to');
}
public function assignedByUser()
{
return $this->belongsTo(User::class, 'assigned_by');
}

BelongsToMany by array values in laravel

How do I store data in users.sport_id:
User class:
public function sport() {
return $this->belongsToMany('App\Sport');
}
Where sports table has:
+----+------------+
| id | sport |
+----+------------+
| 1 | baseball |
+----+------------+
| 2 | basketball |
+----+------------+
Do I add to user.sport_id = 1,2 or save it as array [1,2] and use $casts = ['sport_id'=>'array'];

How can I get a post with all related ones?

Here is my table structures:
// tickets
+----+------------+----------------------+--------+---------+
| id | subject | content | closed | user_id |
+----+------------+----------------------+--------+---------+
| 1 | subject1 | question1 | 0 | 123 |
+----+------------+----------------------+--------+---------+
// answers
+----+----------------------+---------+-----------+
| id | content | user_id | ticket_id |
+----+----------------------+---------+-----------+
| 1 | answer1 | 123 | 1 |
| 2 | answer2 | 456 | 1 |
+----+----------------------+---------+-----------+
Now I need to get a ticket with along all its answers. I can do that using pure SQL like this:
SELECT t.*, a.*
FROM tickets t
LEFT JOIN answers a
ON t.id = a.ticket_id
WHERE t.id = ?
Now I'm using Laravel and I want to do that using with() class (however not sure it is possible). Any idea what change should I make in the models for doing that?
Noted that I can get just a ticket in Laravel like this:
$ticket = Tickets::where('id', $request->id)->get();
First make a hasMany() relationship in your Tickets model class.
public function answers()
{
return $this->hasMany(Answers::class, 'ticket_id', 'id');
}
And then in your controller query
$tickets = Tickets::with('answers')->where('id', $request->id)->get();

How to get record from post table in laravel using eloquen relationships

I have tow table first table is posts table and second table is home_posts table so i want to home_posts table (post_id) throw get record in posts table.
I was used hasMany() relationship in post model but not getting any record. I want only home_posts table post id record from posts table. I want home post table to post table record.
Post table
+----+-----------------+
| id | title |
+----+-----------------+
| 1 | Post 1 |
| 2 | Post 3 |
| 26 | Post 4 |
| 27 | Post 5 |
| 28 | Post 6 |
| 29 | Post 7 |
| 30 | Post 8 |
| 32 | Post 9 |
+----+-----------------+
home_post table
+----+------------+
| id | post_id |
+----+------------+
| 1 | 28 |
| 2 | 29 |
| 3 | 2 |
+----+------------+
In Post model:
public function home_posts()
{
return $this->hasMany('App\HomePost', 'post_id', 'id');
}
In HomePost model:
public function post()
{
return $this->belongsTo('App\Post', 'post_id', 'id');
}
To get post through home_post:
$homePost = \App\HomePost::find(1);
$post = $homePost->post;
or
$posts = \App\HomePost::has('post')->get();
To get home_post through post:
$post = \App\Post::find(1);
$homePost = $homePost->home_posts;
or
$homePost = \App\Post::has('home_posts')->get();
For more detail read this: One To Many
Hope it help you :)

Laravel 5 - Eloquent JOIN confusion

I have two simple tables, cats and breeds:
mysql> select * from cats;
+----+--------+---------------+----------+---------------------+---------------------+
| id | name | date_of_birth | breed_id | created_at | updated_at |
+----+--------+---------------+----------+---------------------+---------------------+
| 1 | Rita | 2008-07-06 | 1 | 2015-05-09 20:40:49 | 2015-05-09 20:50:20 |
| 2 | Muni | 1992-05-15 | 3 | 2015-05-09 20:50:54 | 2015-05-09 20:50:54 |
| 3 | Hector | 2005-01-23 | 4 | 2015-05-09 21:08:23 | 2015-05-09 21:08:23 |
+----+--------+---------------+----------+---------------------+---------------------+
3 rows in set (0.00 sec)
mysql> select * from breeds;
+----+------------+
| id | name |
+----+------------+
| 1 | Domestic |
| 2 | Persian |
| 3 | Siamese |
| 4 | Abyssinian |
+----+------------+
4 rows in set (0.00 sec)
All I want to do is get a list of the cats that are of a certain breed. In the cats table, breed_id is a FK that points to the PK of the breeds table. The example code in my book which is supposed to return a view with all cats of a specific breed returns no results:
The url I am trying is /cats/breeds/Domestic
The view that is generated uses this logic in the routes.php file:
Route::get('cats/breeds/{name}', function($name)
{
$cats = Furbook\Cat::with('breeds')
->whereName($name)
->get();
dd($cats);
});
When I dd($cats) I get zero results even though I have a cat with a domestic breed_id of 1. What have I done wrong here?
EDIT:
I can get it to work with the following hacky code, which first gets the id from the breeds table by querying against the name field, then queries the cats table with that id:
$breed = Furbook\Breed::whereName($name)->get();
$id = $breed[0]['attributes']['id'];
$cats = Furbook\Cat::whereId($id)->get();
How do I make this into one Eloquent query? I see no examples for this kind of query on the Laravel site.
For more information this is how the models look:
class Breed extends Model {
public $timestamps = false;
public function cats()
{
return $this->hasMany('Furbook\Breed');
}
}
class Cat extends Model {
protected $fillable = [
'name',
'date_of_birth',
'breed_id',
];
public function breed()
{
return $this->belongsTo('Furbook\Breed');
}
}
You're asking the system to give you all cats with a name of Domestic - not all cats of the breed name Domestic.
Assuming your model relationships are in order, you could do e.g.
$cats = Furbook\Breed::whereName($name)->first()->cats;
Also, my Burmese cat just hit the monitor; I think she's upset that she's not in the breeds list.

Resources