Is it possible to insert record through chain foreign key relationship in Laravel 5.2 - laravel-5

I have three tables/models :user,employee and employee_disability.
employee has foreign key user_id.
employee_disability contain emp_id foreign key.
Is there a way to perform the following action:
$user->employee()->empdisability()->create(['name'=>$name,'percent'=>$percent]);
Any help is appreciated. Thank You in advance.
MODELS:
class user extends Authenticatable{
public function employees(){
return $this->hasMany('App\Models\employee','user_id');
}
}
class employee extends Model{
public function user(){
return $this->belongsTo('App\Models\user','user_id');
}
public function empdisability(){
return $this->hasMany('App\Models\emp_disability','emp_id');
}
}
class emp_disability extends Model{
public function employee(){
return $this->belongsTo('App\Models\employee','emp_id');
}
}
CONTROLLER
public function storeDisability(Request $request){
$user=Auth::user();
$name=$request->name; $percent=$request->percent;
$user->employee()->empdisability()->create(['name'=>$name,'percent'=>$percent]);
}

$user->employee() returns the query builder for the employee relation, but what you need is the instance.
This should work, notice the lack of parantheses on employee
$user->employee->empdisability()->create(['name'=>$name,'percent'=>$percent]);

Related

Get all records from another table with pivot

I have three tables:
comments
id
comment_links
id | comment_id | link_id
links
id
I want to get all Links associated with each Comment. As you can see, CommentLink should act as a pivot table, but I don't know how to set up the relationships to make this work. I think I need to use the hasManyThrough relationship, but I'm not 100% sure.
Here are my current class relationships (they may be wrong):
Comment.php:
class Comment extends Model
{
public function commentLinks()
{
return $this->hasMany('App\CommentLink', 'comment_id', 'id');
}
public function links()
{
// How do I fetch all links here using the pivot table?
}
}
CommentLink.php:
class CommentLink extends Model
{
public function comment()
{
return $this->belongsTo('App\Comment');
}
public function link()
{
return $this->hasOne('App\Link', 'id', 'link_id');
}
}
Link.php:
class Link extends Model
{
public function commentLinks()
{
return $this->belongsToMany('App\CommentLink', 'link_id', 'id');
}
}
What do I need to do here to make this work?
You have the right idea, just using the wrong class names.
class Link extends Model
{
public function comments()
{
return $this->belongsToMany('App\Comment');
}
}
class Comment extends Model
{
public function links()
{
return $this->belongsToMany('App\Link');
}
}
You don't actually need to have a class for your pivot table, but you can if you want.
This is quite a good guide on how to do this.
https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

Laravel Model Relationship between Students and Courses

I have a Model Student and Course.
Here's what I am trying to get from those models,
Every student is enrolled to one course and the way I save it to the database is like below,
Student Info..., course_id... <- which is basically taken from the Courses table
I want to retrieve the Course name since I already have the course_id stored in the Students table.
I designed the model like:
//Course Model
class Course extends Model
{
public function student(){
return $this->belongsToMany('App\Student');
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->hasOne('App\Course');
}
}
But I don't know how to or what to do next, I am really new to Eloquent approach.
Need help.
I tried to retrieve the Course name using the code below :
$students = Student::all();
#foreach($students as $student)
$student->course->name
....
but I think it is wrong, I'm only getting an error about unknown column
Instead of using belongsToMany for student relation in Course.php model,
Use hasMany function like:
//Course Model
class Course extends Model
{
public function student(){
return $this->hasMany('App\Student');
}
}
//Student Model
Since, student belongs to course, you should use belongsTo instead of hasOne
class Student extends Model
{
public function course(){
return $this->belongsTo('App\Course');
}
}
In order to optimize the query for retrieving all related courses, you can use with Eagar Loading relationship like:
$students = Student::with('course')->all();
#foreach($students as $student)
//If incase there are no course related to the student
$student->course->name ?? null
....
Previous Code :
//Course Model
class Course extends Model
{
public function student(){
return $this->belongsToMany('App\Student');
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->hasOne('App\Course');
}
}
Replace with :
//Course Model
class Course extends Model
{
public function students(){
return $this->hasMany(Student::class); // '\App\Student' also ok
}
}
//Student Model
class Student extends Model
{
public function course(){
return $this->belongsTo(Course::class);
}
}
Why belongsTo at Student Model ?
Inside : When a table primary key assign in another table as foreign key then you should add belongsTo this assigning table.
Here Courses table primary id assigned as foreign key at Students table

Laravel polymorphic relationships return null

I'm trying to join an Order and 2 different OrderDetailType tables.
OrderDetailType1
- id
- order_id
OrderDetailType2
- id
- order_id
Order
- id
- detail_type 'type1' or 'type2'
And I have followed Polymorphic Relations example in official Laravel site and adapted to my code like:
class OrderDetailType1 extends Model {
public function order() {
return $this->morphOne('App\Order', 'type_detail');
}
}
class OrderDetailType2 extends Model {
public function order() {
return $this->morphOne('App\Order', 'type_detail');
}
}
class Order extends Model {
public function type_detail() {
return $this->morphTo();
}
}
And I have put Relation::morphMap() into boot() function in AppServiceProvider class already.
use Illuminate\Database\Eloquent\Relations\Relation;
class AppServiceProvider extends ServiceProvider {
public function boot() {
Relation::morphMap([
'type1' => 'App\OrderDetailType1',
'type2' => 'App\OrderDetailType2'
]);
}
}
The example is different from my code. The difference is both foreign key and the attribute that specifying which table to be joined should be in Order. So I cannot use morphTo() and morphOne() like the example to solve this.
I am confuse which classes should contain morphTo() and morphOne(). And is there any overload to specify which table have foreign key and type?
I use Laravel 5.4. Thank You in Advance.
The _id column has to be in the Order table:
OrderDetailType1
- id
OrderDetailType2
- id
Order
- id
- detail_type
- detail_id
class OrderDetailType1 extends Model {
public function order() {
return $this->morphOne('App\Order', 'detail');
}
}
class OrderDetailType2 extends Model {
public function order() {
return $this->morphOne('App\Order', 'detail');
}
}
class Order extends Model {
public function detail() {
return $this->morphTo();
}
}

Not able to create eloquent relationship with table which have custom primary key

When i'm trying to get user details from company Model i'm getting NULL value.
class User extends Model
{
protected $primaryKey = 'uid';
}
class Company extends Model
{
$table = 'company';
public function users(){
return $this->hasMany('App\User','user_id','uid');
}
}
class RepoController{
public function index(){
$user = Company::where('id',1)->with('user')->get();
/// Returning value but without Users
}
}`
users table should contain company_id and you should define id as company ID because company table doesn't use custom ID:
public function users()
{
return $this->hasMany('App\User', 'company_id', 'id');
}
Or just this:
public function users()
{
return $this->hasMany('App\User');
}
Also, you're trying to load user relationship, but it should be users(), so do this instead:
Company::where('id', 1)->with('users')->get();
I think your ids are in wrong position
try swapping them like
return $this->hasMany('App\User','uid','user_id');

Relationship: belongsTo this model or a different model

We have the following
Manager
[id]
Companies
[id]
[manager_id] not nullable
Stores
[id]
[company_id]
[manager_id] *nullable*
I am looking for a single Eloquent relationship for the manager of every store.
Any suggestions?
Building on your comment #Sanjay S
class Store extends Model {
public function manager() {
return $this->belongsTo('App\Manager');
}
public function getManager() {
if (is_null($this->manager)) {
return $this->company()->manager;
} else {
return $this->manager;
}
Then when you call $store->getManager() you will get the company manager if store manager_id is null
You question is not clear as your relationship in the stores table is like manager_id [nullable] and you are asking for a single Eloquent relationship for the manager of every store. But from my guesses your Eloquent models should be look like this
class Manager extends Model {
public function stores() {
return $this->hasMany(App\Store::class);
}
public function company() {
return $this->hasOne(App\Company::class);
}
}
Company class
class Company extends Model {
public function manager() {
return $this->belongsTo(App\Manager::class);
}
}
Store class
class Store extends Model {
public function manager() {
return $this->belongsTo(App\Manager::class);
}
}
Hope this solution works for you.

Resources