I've created a concept of a Person model having many e-mails. I also have a Company model that can share the same e-mails with People (Person model).
In short:
People OneToMany PeopleEmail ManyToOne Email (classic manytomany unidirectional with a join table)
people { id, firstname, lastname, created }
people_emails { person_id, email_id, main, created }
emails { id, email, created }
as well as:
companies { id, name, employee_count, created }
companies_emails { company_id, email_id, main, created }
emails { id, email, created }
The problem is, that I'd like to store a boolean value called "main" in the join table as follows:
person_id | email_id | main | created
8 | 5 | true | 2014-10-21 16:54:21
...so that I can do this:
Mark Wilson (Person) has 5 emails.
3 of them are his company e-mails (shared): contact#company.com, office#company.com, it#company.com
2 of them are his own.
1 he answers only in his leisure time
1 is his MAIN email: i.e. m.wilson#company.com
Instead of fetching all those 5 emails, I'd like to easily get the primary email just as if it was a regular Person model column:
firstname: Mark (string)
lastname: Wilson (string)
emails: (array)
primary_email: (email object)
I cannot store the "main" property anywhere else, as I want to point, that the relation between Mark and his Email is "main", not the email itself.
Now, I do have this value stored, but the problem is, how to make an entity property like:
class Person {
(...)
/**
* #ORM\ManyToMany(targetEntity="Email")
* #ORM\JoinTable(name="people_emails",
* joinColumns={#ORM\JoinColumn(name="person_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="email_id", referencedColumnName="id", unique=true)}
* )
*/
private $primary_email;
/**
* #ORM\ManyToMany(targetEntity="Email")
* #ORM\JoinTable(name="people_emails",
* joinColumns={#ORM\JoinColumn(name="person_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="email_id", referencedColumnName="id", unique=true)} // A condition?
* )
*/
private $emails;
public function getPrimaryEmail() {
return $this->primary_email; // Single row limit?
}
public function getEmails() {
return $this->emails;
}
(...)
}
The thing is, I would really love to have it as an entity property, just for use in any case possible without the need to write custom repostory functions for the whole Person model.
Or maybe that is a completely wrong way. I'd like to use that property in Twig like:
{{person.primary_email.email}}
To sum up:
I'd like to store a ManyToMany single row relationship depending on joinTable column.
How to do that?
There are many ways to do this and there are also many critical things to say about your design choices. Either way here is an example of one way you could achieve this using two join tables (you need two if you want to use foreign keys).
<?php
interface AddressLink
{
public function getEmail();
public function isMain();
}
trait EmailAddressOwner
{
protected abstract function getAddressLinks();
public function getPrimaryEmailAddress()
{
return $this->getAddressLinks()->filter(function (AddressLink $addressLink) {
return $addressLink->isMain();
})->first();
}
public function getEmailAddresses()
{
return $this->getAddressLinks()->map(function (AddressLink $addressLink) {
return $addressLink->getEmail();
});
}
}
class PersonEmailAddress implements AddressLink
{
private $person; // ManyToOne
private $email; // ManyToOne
private $main; // bool
}
class CompanyEmailAddress implements AddressLink
{
private $company; // ManyToOne
private $email; // ManyToOne
private $main; // bool
}
class Email
{
private $id;
private $address;
}
class Person
{
/**
* #ORM\OneToMany(targetEntity="PersonEmailAddress")
*/
private $emailAddressLinks;
use EmailAddressOwner;
public function getAddressLinks()
{
return $this->emailAddressLinks;
}
}
class Company
{
/**
* #ORM\OneToMany(targetEntity="CompanyEmailAddress")
*/
private $emailAddressLinks;
use EmailAddressOwner;
public function getAddressLinks()
{
return $this->emailAddressLinks;
}
}
Another way would be to include one ManyToMany relation to your Email entity and one ManyToOne relation for the primary e-mail address.
To answer you question in the comments if in twig you do
{{ person.primaryEmail.email }}
It wil actually call the getPrimaryEmail() method on your Person object. Which you can implement like I've outlined above. That way you don't need to have this extra property.
Related
I'm trying to query multiple tables using Laravel Eloquent Models with one to one, one to many and many to many relationships.
I have a forms table, a brands table a users table and a brand_groups pivot table.
Each form has one brand and one user:
forms
ID
user_id
brand_id
Brands do not have any foreign keys:
brands
ID
Users do not have any foreign keys:
users
ID
And there is a pivot table to create a many to many relationship for creating brand groups that have many users like brand members:
brand_groups
brand_id
user_id
I'm trying to get all the forms that belong to a user either by a direct ownership (forms.user_id) or by brand membership, all the forms from all the brands that the user is a member through brand_groups many to many pivot table.
For example, we have 2 brands, 2 users and 1 user is a member of 1 brand:
brand(ID: 1)
brand(ID: 2)
user(ID: 1)
user(ID: 2)
brand_group(brand_id: 1, user_id: 1)
form(ID: 1, user_id: 1, brand_id: null)
form(ID: 2, user_id: null, brand_id: 1)
form(ID: 3, user_id: 2, brand_id: 1)
form(ID: 4, user_id: 1, brand_id: 2)
Using Laravel Eloquent Models (not direct DB facade calls), I'd like to retrieve all the forms that belong to a user. For the user(ID:1) there are 3 forms:
form(ID:1) direct user ownership
form(ID:2) user is a member of brand(ID:1) group which is the brand of form(ID:2)
form(ID:3) user is a member of brand(ID:1) group which is the brand of form(ID:3)
I gave it a shot using Eloquent: Relationships - Has Many Through:
Has Many Through
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation.
I have tried it like this:
class User extends Model
{
public function forms()
{
return Forms::hasManyThrough(
Form::class,
BrandGroups::class,
'brand_id',
'brand_id',
'id',
'form_id',
)->where('id', $this->id);
}
}
But I get errors like:
BadMethodCallException with message 'Call to undefined method App\Models\Form::brand_groups()'
EDIT
After some digging, I have managed to come up with the working MySQL code that will return all the forms for a user:
SELECT * FROM `forms`
WHERE EXISTS (
SELECT `brand_id`, `user_id`
FROM `brand_groups`
WHERE `forms`.`brand_id` = `brand_groups`.`brand_id`
AND `brand_groups`.`user_id` = 1
) OR `forms`.`user_id` = 1
Now I just need to convert that query to an eloquent model relation.
Eloquent Models
User.php
class User extends Authenticatable implements MustVerifyEmail
{
public function brands()
{
return $this
->belongsToMany(Brand::class, 'brand_groups')
->using(BrandGroups::class)
->as('member');
}
public function forms()
{
return $this->hasMany(Form::class, 'user_id');
}
}
Brand.php
class Brand extends Model
{
protected $table = 'brands';
public function forms()
{
return $this->hasMany(Form::class);
}
public function members()
{
return $this
->belongsToMany(User::class, 'brand_groups')
->using(BrandGroups::class)
->as('member');
}
}
Form.php
class Form extends Model
{
protected $table = 'forms';
public function owner()
{
return $this->belongsTo(User::class);
}
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
UPDATE
I manage to find a query to get all forms related to a user like this:
class User extends Authenticatable implements MustVerifyEmail
{
...
public function allForms()
{
return Form::where(function ($q) {
$q->whereExists(function ($q) {
$q->from('brand_groups')
->where('forms.brand_id', DB::raw('brand_groups.brand_id'))
->where('brand_groups.user_id', $this->id);
})->orWhere('owner_id', $this->id);
});
}
}
How this can be converted to a direct User model eloquent relationship?
Have you tried to Eager Load the User model relationships?
Edit
Firstly: the pivot table name should be the singular -snake_case- name of both tables and should be in alphabetical order (brand_user)
Next, try the following:
return User::where(‘id’, $this->id)->with([‘forms’,‘brands.forms’)->get();
This should return the Forms with direct ownership plus the user Brands and their associated Forms
How do I query in Laravel Eloquent the following criteria
having project, employees tables and a many to many binder project_member table, I want to get projects where a project is owned by logged in user as a team member.
in my Project model I have
/**
* #return mixed
*/
public function members()
{
return $this->belongsToMany('App\User', 'project_team', 'id', 'project');
}
and user table
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function team()
{
return $this->belongsToMany('App\Project', 'project_team', 'employee', 'project');
}
and I want to get all projects where logged in user is a member of a given project
I Have three tables
#1 Table timeline which is my reference table with an Auto incremented ID which is stored in column id
#2 timeline_videos
#3 timeline_else
What happens is on post if a video is uploaded with the post
it will go into Table #2 ,anything else goes into Table #3.
#2-3 have the Auto Increment Id from the Table timeline stored in a column pid
On query of The Timeline I need to join both tables data using id=pid
so I can use the rest of the Relational Data with the post.
I have done a bit of research and can't seem to find a method for doing so.
So far the code I have
Controller
$groupposts = timeline::where([
['owner','=',$owner],['id','<',$lastid],
])
->join('timeline_videos','timeline.id','=','timeline_videos.pid')
//->join('timeline_else','timeline.id','=','timeline_else.pid')
->orderBy('id','desc')
->limit(5)
->get();
This works with no errors with the second Join commented out but I need to also grab the timeline_else data .
Update --
I have now decided to use Eloquent Relationships to join the tables,
my question now is what type of relationship do I have between the
tables?
I realize it basically needs to be able to switch between two tables to
grab data based on the fact that timeline_videos and timeline_else will not be "JOIN" but separated by type .
The tables need to Join with table #1 timeline based on a column I now have named type for clarifying where to look and matching/joining using the id = pid
You can use relationships.
it sounds like timelines has many videos and has many video failures
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
you would have a model for each table and set up the relationships
timelines model:
public function videos()
{
return $this-> hasMany('App\Videos');
}
public function videoFailures()
{
return $this-> hasMany('App\videoFailures');
}
videos model:
public function timeline()
{
return $this->belongsTo('App\Timelines');
}
videos failures model:
public function timeline()
{
return $this->belongsTo('App\Timelines');
}
You can then go:
$timeLine = Timmeline::find($id);
to find videos of the time lines you would do:
$videos = $timeLine->videos();
to find else:
$videoElse = $timeLine-> videoFailures();
By using some of what Parker Dell supplied and a bit more trial and error
My Models Looks like
timeline
class timeline extends Model
{
protected $table ='timeline';
public $timestamps = false;
public function videos()
{
return $this->hasMany('App\timeline_videos','pid','id');
}
public function else()
{
return $this->hasMany('App\timeline_ect','pid','id');
}
}
timeline_ect.php ,I changed the name of the table
class timeline_ect extends Model
{
protected $table='timeline_ect';
public $timestamps = false;
public function timeline()
{
return $this->belongsTo('App\Models\timeline','pid','id');
}
}
timeline_videos
class timeline_videos extends Model
{
protected $table='timeline_videos';
public $timestamps = false;
public function timeline()
{
return $this->belongsTo('App\timeline','id','pid');
}
}
Then Lastly my Controller
$timeline = timeline::with('videos','else')
->orderBy('id','desc')
->limit(5)
->get();
So far no Problem query is correct.
I'm trying to figure out how to find a group of objects based on a layered relationship. I have 3 entities like so:
Referral --> manyToOne --> Patient --> manyToOne --> Payor
How do I find all referrals a given payor?
I'm using symfony3 with mysql and doctrine. My entities:
class Referral
{
// usual stuff
/**
* #ORM\ManyToOne(targetEntity="Patient")
*/
private $patient;
}
class Patient
{
// usual stuff
/**
* #ORM\ManyToOne(targetEntity="Payor")
*/
private $payor;
}
class Payor
{
// usual stuff
}
Obviously I could make the relationships birectional, for example so I could do something like this in my controller:
$patients = $payor->getPatients();
foreach ($patients as $patient) {
$referrals = $patient->getReferrals();
}
And then collect these into an appropriate array, but this seems messy and I'd rather do it all in a single database query in my repository. Can that be done?
you can find all referrals for a given payor using a query.
in ReferralRepository
public function findReferralsByPayor(Payor $payor)
{
$qb = $this->createQueryBuilder('r');
$qb
->join('BUNDLENAME:Patient', 'p', 'WITH', 'p.id = r.patient')
->where('p.payor = :payor')->setParameter('payor', $payor)
;
return $qb->getQuery()->getResult();
}
I have an app that handles user info, and one of the pieces of data we collect is what school(s) they're attending. We have a User object, School object, and a UserSchool object.
This is the user_schools table:
user_id (int),school_id (int)
With the following records for instance:
100, 20
200, 500
200, 10
300, 10
I'm trying to get all schools for the current user (say user 200). This is my UserSchool object:
class UserSchool extends Model
{
var $table = 'user_schools';
function user() {
return $this->belongsTo('User');
}
function school() {
return$this->belongsTo('School');
}
}
In User I have the following relations defined:
public function schools()
{
return $this->hasManyThrough('School', 'UserSchool');
}
public function userSchools()
{
return $this->hasMany('UserSchool');
}
When I var_dump($user->schools) I get no results, even though I know it should be returning multiple Schools. What am I doing wrong? I'm sure this must have been asked before but I don't know what the actual term for this intermediate type of relationship is (bridge table? pivot table?).
Edit: Either way, most of the examples I've looked at haven't worked. I've also tried:
public function schools()
{
return $this->hasManyThrough('School', 'UserSchool', 'school_id');
}
In fact you don't need to have UserSchool object here for this relationship
For User model you can use create the following relationship:
public function schools()
{
return $this->belongsToMany(School::class, 'user_schools');
}
And now you can get schools of user using something like this:
$user = User::find(1);
foreach ($user->schools as $school)
{
echo $school->name;
}
This is standard many to many relationship