Laravel relationships (one to many) - laravel

I am new to Laravel and maybe somebody can give me an example for this.
I have two tables - Auhors and Books and two views - authors.index and books.index.
I know how to display all the books related to author in authors.index, but the question is, how to display all authors related books in books.index view?
My models and BookController:
Authors
Books
BooksController

You need to use the opposite function belongsTo into your Books model.
public function authors() {
return $this->belongsTo(Authors::class, 'author_id', 'id');
}
You can find more info here

Related

How to search for all associations in a relationship tree in Laravel?

I'm having a problem. I have tables that relate:
internal_clients->subsidiaries->departments->job_titles->users
I also have their respective models.
My doubt is:
How do I get all the data associated with users from the top of the tree (internal_clients)
?
I'm trying to follow the Laravel documentation using hasManyThrough.
However, in the documentation it explains only how to do it in a chain of three tables. They teach how to place an intermediate table (model) as the second parameter of the hasManyThrough method (BaseClasse::class, IntermediaryClass::class).
However, in my case that has several tables between users and internal_clients, how would I do this? What would be the intermediate table?
I would like to make a query that returns the user's internal_client, subsidiary, department and jobTitle (associated with users).
I'm trying to do it this way:
Model InternalClient
public function users()
{
return $this->hasManyThrough(User::class, InternalClient::class);
}
Controller UserController
public function allRelations($internalClientId)
{
$internalClient = InternalClient::find($internalClientId);
$users = $internalClient->users;
return response()->json($users, 201);
}
The InternalClient id arrives at the controller above.
When I access the route, the error below is returned:
In short: I would like to know if there is a way to get all the data (from all tables that are in this hierarchical tree) that are associated with the User.
I couldn't find an answer on the Stackoverflow PT-BR.
Thank you!

How to make left join in many to many relationship laravel

I am new in laravel. I have 3 tables
users
ingredients
user_ingredients(pivot table)
Now i have established many-to-many relationship but I have a special requirement that I want to get matching records(which is done) with all the ingredients in ingredients table. I can do it using query_builder or raw but I want to do it in eloquent.
I have searched about 4 hours to find any solution in eloquent but did not found.
Here is my code
User Model
public function ingredients()
{
return $this->belongsToMany('App\Ingredient', 'user_ingredients');
}
Ingredient Model
public function user()
{
return $this->belongsToMany('App\User', 'user_ingredients');
}
Controller Code
$ingredients = $user->ingredients()->get();
Query Builder query
select ingredients.*,user_ingredients.liked from ingredients LEFT JOIN user_ingredients on ingredients.id = user_ingredients.ingredient_id and user_ingredients.user_id=129
I have checked has(),with() but nothing according to my requirement.
Please help me. Thanks
If I understand your question correctly, you are just trying to access all the ingredients on the user model? In that case, you should be able to just do $user->ingredients
You can access the relationship as a property on the user object. It's some behind the scenes Laravel magic that handles this.

Laravel 3 tables on belongsToMany relation

Based on the official Laravel documentation I found that :
$books = App\Book::with('author.contacts')->get();
In this case, imagine we have a structure like this :
books
books_authors
authors
contacts
books_authors_contacts
That's just an hypotetic case but I would like some more information : what about if I would like to retrieve all authors contacts for this specific book, imagining that for a specific book multiples authors could have multiple contacts (such contacts are linked through both authors and books as the entity books_authors_contacts says)
Is it possible to retrieve it through Laravel with eager loading with a belongsToMany relation?
By using the example below, it would just retrieve all of the contacts of an author no matter the book is.
Thanks you in advance!
There is tricks to gain this functionality in a very complex fashion, see this post. In a more practical sense, when these cases arrive in a professional environment, you often end up doing a method that aggregates this data. This can be done in multiple ways, this is an approach i feel is fairly easy and readable.
public class Book
{
public function contacts()
{
$contacts = new Collection();
$this->authors->each(function(Author $author) use($contacts) {
$contacts->concat($author->contacts);
})
return $contacts;
}
}
Offcourse for the eager loading, you have to remember to include the whole structure. For more Laravel approach contacts can be made as a Eloquent Mutator.
$book = App\Book::with('authors.contacts')->find(1);
$contacts = $book->authors();

laravel 3 way pivot

I've one many to many relationship between Entities and Affiliated Tables,
basically an affiliated can attend to many entities(example, medical services, dentist offices). One Entity can be visited by one or many affiliated.
Additionaly , one or more benefits can be occupied by one affiliated in a particular entity. As shown in the image.
I want to be able to answer queries like, which benefits where used by the affiliated in a particular entity.
Should i create a new Model, how should i rewrite the many-to-many relationship for ORM.
Thanks in advance!
Don't need a Affiliated_has_Entities model.
You could write the relationships as below, remember to check for arguments and its order in the belognsToMany relationship (sorry for misspelled words)
Entities model
public function afilliateds(){
return $this->belongsToMany('Afilliated', 'Afilliated_has_Entities');
}
Afilliated model
public function entities(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
public function benefits(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
Benefits model
public function entites(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
And so on..
I hope it helps

Display parent-child relation yii2

I am looking for some way to implement the following thing with yii2:
Lets imagine we have the following structure:
- authors table.
- Books table
Each author -> has written 1 or more books.
What I want to do is to display on a view, the details of an author, and under it, a gridview of all the books it has written. After that, control buttons to create/ remove new books for that current author, along with a gridview of the books which belongs to the current author... In some other words, a master-detail view.
How I should retrieve the data of the books? From the same controller for Authors?
I have already implemented the table relations between authors and books, in the Author's model
Thanks in advance, any help is welcome!!
If the you have the following relation in your Author model:
public function getBooks()
{
return $this->hasMany(Books::className(), ['author_id' => 'id']);
}
After declaring relations, getting relational data is as easy as accessing a component property that is defined by the corresponding getter method:
$author = Author::findOne(1);
$books = $author->books;
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
The solution I found at the end was to :
On the Author's controller, I modified the "view" action, so I could a "books" activeDataprovider, and then filtering it by "author id":
public function actionView($id)
{
//get current author
$author=$this->findModel($id);
$books_search = new BookSearch();
//get the related books for current author
$written_books = $books_search->search(['bookSearch'=>['id_author'=>$id]]);
return $this->render('view', [
'author' => $author,
'books_search'=> $books_search,
'books'=>$written_books,
]);
}
Then I could create on the Author's view, a gridview with the books written by the current author

Resources