I've a tables what looks that:
Users:
id | username | password | ...
Users_Services
id | user_id | service_id | active | paidTo
And Services:
id | title | description | type | price | active
I want get services of current user with all data about it from another table, so my relationship should looks:
I don't know how can I do that on "User_Services" class, in Controller I've:
$services = User::find( Auth::user()->id )->services;
User class:
public function services() {
return $this->hasMany('User_Services');
}
And Services class:
public function user_services()
{
return $this->hasManyThrough('User_Services', 'User', 'service_id');
}
Now how about User_Services class, how can I do that relationship?
From User class you can declare both relationships.
Edit: I got confused by the arrows: If the relation is 1-N_1-N
class User extends Eloquent {
public function services()
{
return $this->hasManyThrough('Services', 'Users_services');
}
public function usersServices()
{
return $this->hasMany('Users_services');
}
}
If it is many to many 1-N_N-1
class User extends Eloquent {
public function services()
{
return $this->belognsToMany('Services', 'Users_services');
}
}
class Services extends Eloquent {
public function services()
{
return $this->belognsToMany('Users', 'Users_services');
}
}
I believe you are actually looking for a many-to-many relationship which in Laravel is going to be defined with the belongsToMany() function. You can set those up like so...
class User extends Eloquent {
public function services()
{
return $this->belongsToMany('Service')->withPivot('active', 'paidTo');
}
}
class Service extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
The withPivot() part is grabbing those additional columns you have on your User_services table.
Now getting a user's services should be very easy and can be done like so...
$services = Auth::user()->with('services');
foreach($services as $service) {
echo $service->description;
// If you need to display information from the pivot table, that can be done like so.
echo $service->pivot->paidTo;
}
Related
I have 3 tables (Models)
Advertise :
id
title
...
Value:
id
title
amount
....
Field:
id
name
title
...
and my pivot tables is like:
advertise_id
value_id
field_id
how can I set relations in my models and do a crud(please give me an example)?
all the relations are many to many
3 model classes accordingly:
class Advertise extends Model
{
public function fields()
{
return $this->belongsToMany(Field::class);
}
public function values()
{
return $this->belongsToMany(Value::class);
}
}
class Field extends Model
{
public function advertises()
{
return $this->belongsToMany(Advertise::class);
}
public function values()
{
return $this->belongsToMany(Value::class);
}
}
class Value extends Model
{
public function fields()
{
return $this->belongsToMany(Field::class);
}
public function advertises()
{
return $this->belongsToMany(Advertise::class);
}
}
I have been trying to figure out how to implement a matching system but have become stuck.
I've managed to build a query within a controller which does exactly the same thing as I want it to do, but I would like to convert it to an Eloquent Model since images are broken and also can access some functions inside my Model.
Here's the query builder within the controller that I wish to convert (if it's possible at all)- I am checking if users have both "liked" each other (similar to Tinder):
class MatchedEmployersController extends Controller
{
public function index()
{
$matches = DB::table('applicant_likes')
->join('employers', 'employers.id', '=', 'applicant_likes.liked_employer_id')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('employer_likes')
->whereRaw('employer_likes.employer_id = applicant_likes.liked_employer_id');
})
->get();
return view('applicant.employers.matched', compact('matches'));
}
}
Here's the Applicant model where below I extracted the logic into a usable Traits
App\Models\Applicant
class Applicant extends Authenticatable
{
use Notifiable, LikeableEmployer, MatchableEmployer;
//
public function getAvatarAttribute($value)
{
return asset($value ?: '/images/default-avatar.jpeg');
}
}
App\Trais\LikeableEmployer
trait LikeableEmployer
{
public function likeEmployer(Employer $employer)
{
return $this->likedEmployers()->save($employer);
}
public function unlikeEmployer(Employer $employer)
{
return $this->likedEmployers()->detach($employer);
}
public function toggleLikeEmployer(Employer $employer)
{
if ($this->likingEmployer($employer)) {
return $this->unlikeEmployer($employer);
}
return $this->likeEmployer($employer);
}
public function likingEmployer(Employer $employer)
{
return $this->likedEmployers()->where('liked_employer_id', $employer->id)->exists();
}
public function likedEmployers()
{
return $this->belongsToMany(Employer::class, 'applicant_likes', 'applicant_id', 'liked_employer_id');
}
}
finally, here's where the matched logic should be placed
namespace App\Traits;
use App\Traits\LikeableApplicant;
use App\Traits\LikeableEmployer;
trait MatchableEmployer
{
use LikeableApplicant, LikeableEmployer;
public function matchedEmployers()
{
//
}
}
You need to create a table where you will store the matches. Let's take the following example.
relationships table: id | from | to, It's a match if we have a pair. Example:
id | from | to
1 | 1 | 2
2 | 2 | 1
Now create Relationship Model
class Relationship extends Model
{
public static function getMatch($user_id)
{
return self::leftJoin('relationship reverse', 'relationship.to', '=', 'reverse.from')->where('relationship.from', 'reverse.to')->where('relationship.from', $user_id)->get();
}
}
Now you can simply call User::getMatch('any_user_id');
First of all, create the model for every table you used in this query, then add the following relationship.
In ApplicantLike Model
public function employer(){
return $this->belongsTo('App\Employer','liked_employer_id','id');
}
In Employer Model
public function likes(){
return $this->hasMany('App\EmployerLike','employer_id','id');
}
Final in your MatchedEmployersController
public function index()
{
$matches = ApplicantLike::with('employer','employer.likes')
->has('employer')
->has('employer.likes')
->get();
// dd($matches); // try with this first
return view('applicant.employers.matched', compact('matches'));
}
Try the above code, I converted your given code into ORM, but I think that you are implementing the wrong logic for what you need. If anything will not work fine just reply to me I will help you.
Using Laravel 5.6, let's say I have the following database tables:
networks users vlans
-------- ----- -----
id id id
network_id network_id
vlan_id
And these relations:
class Network extends Model {
public function users() { return $this->hasMany("User"); }
public function vlans() { return $this->hasMany("Vlan"); }
}
class User extends Model {
public function network() { return $this->belongsTo("Network"); }
public function vlan() { return $this->belongsTo("Vlan"); }
}
class Vlan extends Model {
public function network() { return $this->belongsTo("Network"); }
public function user() { return $this->hasOne("User"); }
}
My question is: given a Network ID, is there an easy way to determine which Vlan objects are not assigned to a User?
This is very early stages (and I'm quite new to Laravel) so if I've screwed up the relationships I have no qualms about starting over. I've considered changing things so that the vlans table has a user_id foreign key but that seems backwards. (And it would just leave me with the same question in reverse: how to find all the User objects that don't have a Vlan assignment!)
You can add a scope to your Vlan model:
public function scopeNotAssigned($query, $id)
{
return $query->whereNotIn(
'id',
User::where('network_id', $id)->select('vlan_id')->get()->pluck('vlan_id')->toArray()
);
}
Then suppose you have a network:
$network = \App\Network::first();
You can retrieve the non-assigned vlans in the network like this:
$vlans = \App\Vlan::notAssigned($network->id)->get();
Otherwise you can also add a relationship with the users in your Vlan model:
public function user()
{
return $this->hasOne('App\User');
}
Then you could use the whereDoesntHave function:
$vlans = Vlan::whereDoesntHave('users', function ($query) use ($network) {
return $query->where('network_id', $network->id);
})->get();
I have 3 tabels: users, teachers And posts.
users:
id - integer
name - string
teachers:
id - integer
teacher_id - integer
user_id - integer
name - string
posts:
id - integer
user_id - integer
title - string
User Model:
class User extends Model
{
public function teachers()
{
return $this->hasMany('App\Teacher');
}
}
Teacher Model:
class Teacher extends Model
{
public function posts()
{
return $this->hasMany('App\Post', 'user_id','teacher_id');
}
}
? Question is How can I use sth like this:
$user = User::find(1);
$teacher_posts = $user->teachers()->posts
I'm sort of new to laravel but here is my take.
What I have realized is that typically your many to many relationships will require a pivot table.
users:(id, name)
teachers:(id, teacher_id, name)
teacher_users:(id, user_id, teacher_id)
posts:(id, user_id, title)
And your Eloquent models will look like this.
class User extends Model
{
public function teachers()
{
return $this->belongsToMany('App\Teacher');
}
public function posts()
{
return $this->hasMany('App\Post');
}
}
class Teacher extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
$user = User::find(1);
$user_posts = $user->posts();
Check out the documentation here for more details
I am trying to develop a blog using Laravel 5 in which i have to show comment along with user on post.
Here is my database table schema.
User
id
name
Posts
id
post_content
user_id
Comments
id
comment
user_id
post_id
Here is my User Model
public function posts()
{
return $this->hasMany('App\Models\Posts');
}
public function comments(){
return $this->hasManyThrough('App\Models\Comments','App\Models\Posts');
}
Here is my Posts Model
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('Ap\Models\Comments');
}
Here is my Comment Model
public function posts()
{
return $this->belongsTo('App\Models\Posts');
}
public function user(){
return $this->posts->name;
}
Here is my code how i am accessing user name
$comments = Comments::find(1);
$comment['comment'] = $comments->comment;
$comment['user_name'] = $comments->name;
$comment['post_id'] = $comments->posts->id;
may be i am not getting in right direction? if i am doing right then why it is not working.
In laravel 5 you do not call the model as you are doing. since the models are stored in the app folder just call like. Plus I think you need to define the relationship
class User extends Model {
public function phone()
{
return $this->hasOne('App\Phone');
}
}
class Phone extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
$phone = Phone::find(1);
For the case of foreign keys and more regarding the Eloquent relationships in laravel 5 just follow the documentation on the laravel website. Make sure to look at dynamic properties of that are allowed by eloquent
http://laravel.com/docs/5.0/eloquent