Laravel Get Data From Relation Table - mysql

I'm building a project with Laravel 7.28. I have three tables named; projects, tags and project_tags. in project_tags table there is project_ids and tag_ids. It looks like this:
I need to get all projects with their tag and secondly I need to get projects with certain tag. So What should I do in models? Which function and how should I use? And how can I get data?
I discovered rtconner/laravel-tagging package but is it the correct way to do it? Thanks for your help

You might want to create a many to many relationship between projects and tags.
class Project extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class, 'project_tags')->withTimestamps();
}
}
Then:
// Get all projects with their tags.
Project::with('tags')->get();
// Get projects contain certain a certain tag.
Project::whereHas('tags', function ($query) {
return $query->where('tag', 'some value');
})
In addition, tags tend to be a polymorphic many to many relationships. So if you want to manually handle tagging in the long term, I suggest designing that way.
Also, checkout spatie/laravel-tags package.

Related

relationships with multiple level eloquent [duplicate]

I know this question has been asked but my situation is different.
I have Post model with relationship to Comment model defined:
/*Post Model*/
public function comments(){
return $this->hasMany('comment');
}
and Comment model which each comment belong to one user :
/comment model/
public function user(){
return $this->belongto('user');
}
now I want to query all post and eager load comments (of each post) along with user information who post the comment.
anyway to make it work please ?
thank you.
What you want is nested eager loading, scroll down a bit and you will see it.
Quoting the docs:
To eager load nested relationships, you may use "dot" syntax. For
example, let's eager load all of the book's authors and all of the
author's personal contacts in one Eloquent statement:
$books = Book::with('author.contacts')->get();
In your case
$posts = Post::with('comments.user')->get();

How select a single row october cms

How to select a single row on october cms?
How can a simple thing be so complicated here?
I thought it would be something to help us and not to disturb something that is as simple as
SELECT * FROM `engegraph_forms_membros`
Here it's like fighting against demons without a bible, oh god why?
Why make the query difficult for newbie?
I understand you don't speak English natively but you should watch every single one of these videos.
Does the record belong to a model in a plugin? Here are the docs on how to work with models.
You make a plugin, set the database which creates models, and then make components to be ran in your CMS Pages.
In a component.php file you can have something like this: Here I am calling the model class Agreements with use Author\Plugin\Models\Agreements;. This allows me to run a function/method to retrieve all agreements or one agreements using laravel's eloquent collection services.
Lets say we have the ID of a record. Well we can either call on the Agreements model with ::find or with ::where. You will noticed I have two functions that essentially do the same thing. ::find uses the primary key of the models (in my case the id) and will return a singular record. *Note that find can take an array and return a collection of records; like ::where. Using ::where we are going to look for the ID. *Note ::where always returns a collection which is why I have included ->first().
<?php namespace Author\Plugin\Components;
use Session;
use Input;
use Crypt;
use Db;
use Redirect;
use Illuminate\Contracts\Encryption\DecryptException;
use October\Rain\Support\Collection;
use Author\Plugin\Models\Agreements;
class GetAgreement extends \Cms\Classes\ComponentBase
{
public function componentDetails()
{
return [
'name' => 'Get one agreement',
'description' => 'Get an agreement to change or delete it'
];
}
public function onRun() {
$this->page['agreement'] = $this->getWithFindAgreement;
}
public function getWithFindAgreement() {
$id = 1;
$agreement = Agreements::find($id);
return $agreement;
}
public function getWithWhereAgreement() {
$id = 1;
$agreement = Agreements::where($id)->first();
return $agreement;
}
}
If for some reason you aren't working with models, here are the docs to work with Databases. You will have to register the use Db; facade.
Here call the table you want and use ::where to query it. *Note the use of ->first() again.
$users = Db::table('users')->get();
$user = $users->where('id', 1)->first();
There are two simple ways to select a single row:
This will give you the'first' record in the selected recordset.
SELECT top 1 * FROM `engegraph_forms_membros`
This will select all the records that meet the predicate requirement that the value of <columnname> is equal to <value>
SELECT * FROM `engegraph_forms_membros` where <columnname>=<value>
If you select a record where multiple values meet that requirement, then you can (randomly) pick one by combining the solutions...
SELECT top 1 * FROM `engegraph_forms_membros` where <columnname>=<value>
But be aware that without an ORDER BY clause, the underlying data is unordered and prone to change uncontrollably, which is why most people (including your boss) will find the use of 'Top' to be improper for real use.

How to get a related model through a pivot table in Laravel?

i have a bit of a problem in my Laravel 5.4 application, in my database i have several entities that are related through a central model called Content like such.
Actor -> actors_contents -> Content
Category -> categories_contents -> Content
And then i have three other entities that are "contents" like Video, Photo etc...
Video (content_id) -> Content
Photo (content_id) -> Content
Stream (content_id) -> Content
What i want is to be able to, for instance access all of the Videos for a particular Actor from the Actor model, while also being able to directly get the Actors inside of the Video Model.
So essentially, get the content_id for the current Actor from a pivot table and then find the Videos that match it.
I was trying to use hasManyThrough but after reading for a while i found that it doesn't work with Many-to-many relationships, so my question is how can i make this work otherwise?
I don't want to have to define my own Relationships or anything like that, i could i guess create a method on the Model that simply does some joins to get the values i want, but does that have implications behind the scenes when compared to Laravel's Relationships?
For one
->with(['relation'])
Would no longer work with this relationship and as such i wouldn't be able to eager load it and that might be a bit of a problem, so how would you guys solve this problem?
Thank you in advance for your help.
What I want is to be able to, for instance, access all of the Videos for a particular Actor
One way to do that is to use whereHas():
$actorName = 'John Travolta';
Video::whereHas('content', function ($q) use ($actorName) {
$q->whereHas('actors', function ($q) use ($actorName) {
$q->where('name', $actorName);
});
})->get();

Yii2 activeDropDownList fundamentals

I'm new to Yii2 but not to MVC (trying to move my focus from MS to Yii2). I've scaffolded up an app from my DB using gii. I have a table called track I have a table called music_category. There's a n:n relationship via a link table called track_has_music_category. My track model (as scaffolded by gii) has a function
public function getMusicCategories()
{
return $this->hasMany(MusicCategory::className(), ['id' => 'music_category_id'])->viaTable('track_has_music_category', ['track_id' => 'id']);
}
But that is for retrieving the categories that have been 'link'ed to this track. So I guess I need something like
<?= Html::activeDropDownList(theCategoryModel (syntax here??), 'id', ArrayHelper::map(theCategoryModel->findAll(),'id', ''description)) ?>
Well, something like that. I feel as though the online reference could do with a few worked examples.
Any help much appreciated.
Cheers
Mark
Let's say we want to attach some categories to a track model ($model):
echo Html::activeCheckboxList($model, 'musicCategories', ArrayHelper::map(MusicCategory::findAll(),'id', ''description))
We use activeCheckboxList here since it's a multiple relation.
Although you will need to add extra $model logic to save these relations.
Have a look at this How do I work with many-to-many relations in Yii2

Doctrine complex entities

Let's say i have two Doctrine entities:
Users and Messages
Every user can have 'n' messages.
Now I want to display the mailbox for a user so I fetch the user entity from the ORM and from this entity I get all messages. No problem so far.
But now i want to have some more complexe filtering of the messages. For example: Max age, Max count, blacklisting some words etc. So the default getter method of the entity for getting the messages isn't enough.
How can i solve this?
A entity repository is the first thing i found but then i have to ask this repoitory from outside of the user object which breaks the relationship of user and message (repository->getMessagesForUser(userId,...) instead of user->getMessages(...)) which doesn't look like a 'clean' OOP solution for me.
Another way i could think of is to ignore all this fancy ORM stuff and write my own models and getting the informations from the database on the lowest ORM or even DBAL layer. And ether wrap the entity or fill the fields of my own models manually. But then i ask myself: "Why did i use Doctrine?".
So what's the best practice for this case. By the way i use Symfony 2.
In this specific case, I would definitely make the Message its own aggregate, and therefore would create a Repository for it, and remove the relationship from User to Message. The User can have many Messages anyway, so it would be very inefficient to use the other approach.
I would then create specific methods in the MessageRepository:
class MessageRepository
{
public function findByUser(User $user) {
// ...
}
public function findReadMessagesByUser(User $user) {
// ...
}
}