how to defined Custom foreign key in Laravel's "belognsToMany" method? - php

table MemberOwner:
id | name | time
table Member:
id | sex | age
talbe MemberOwner_Member:
id | ownerid | memberid
and this is my relationship-defined code:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','?','?');
}
}
look at the question mark above,how to fill with it?thank you,I've tried
ownerid,memberid
and
memberid,ownerid
but neither of them works,I need you help ,thanks again!

Try this:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','foreign key','localkey');
}
}
Here we are specifying this in MemberOwner model and for MemberOwner_Member table foreign key would be ownerid and if you want to specify local id then it would be id which is primary key there.
Use this:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','ownerid');
}
}
And this will work also if you want to specify local key.
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','ownerid','id');
}
}

Related

LARAVEL ELOQUENT - I want to add column from user table to a relation table

I am not much familiar with eloquent orm in laravel
I have 3 tables they are
-- leads
|
Lead_appointments
and users table
since lead_appointments belongs to leads references id on leads by lead_id
the leads_appointments has a column called created_by with user's id in it
I am trying to query user's name and email along with the result as another column when query using eloquent
Lead Model
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
}
}
My eloquent query in controller
return $this->lead->with('appointments')->find($id);
the result is like this
In under appointments i also want user email and name along with created by in it
But I couldn't figure it out
Add a relation to LeadAppointment model like this:
class LeadAppointment extends Model
{
public function users()
{
return $this->belongsTo('App\Models\User', 'created_by');
}
}
and change leads model like this:
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
}
}

how to return all value in pivot table in Laravel 5.4

i got pivot table that consist of
account_id
article_id
created_at
updated_at
how to retrieve all of them in View. I have 2 model account and article
class Account extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
}
}
class Article extends Model
{
public function accounts()
{
return $this->belongsToMany('App\Account','accountsarticles')->withPivot('account_id','article_id')->withTimestamps();
}
}
And also i have controller like this
class AccountsArticlesController extends Controller
{
public function index()
{
/*If i use this 1 i can get all of column data*/
$accountsarticles=DB::table('accountsarticles')->get();
/*If i use this 1 i only get created_at and updated_at*/
$acc = Account::all();
return view('accountsarticles.index',['accountsarticles'=>$accountsarticles]);
}
}
For now i retrieve it like this without using MVC
#foreach($accountsarticles as $article)
<tr>
<td>{{$article->created_at}}</td>
<td>{{$article->updated_at}}</td>
<td>{{$article->account_id}}</td>
<td>{{$article->article_id}}</td>
</tr>
#endforeach
I wondering how to retrieve all column in that pivot so i can show all data in that column when the view returned.
Using the following syntax $model->pivot->field_name
In your case, it'll be:
//to fetch account id
$article->pivot->account_id
//to fetch article id
$article->pivot->article_id

how to use a simple Relationships in laravel

I have two tables like below:
users table:
id - fname - lname
users_projects table:
id - user_id - title
my models are inside a directory called Models:
Users model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//
public function usersProjects()
{
return $this->belongsTo(UsersProjects::class);
}
}
UsersProjects model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UsersProjects extends Model
{
protected $table = 'users_projects';
//
public function users()
{
return $this->hasOne(Users::class);
}
}
now, I want to show last projects :
$projects = UsersProjects::limit(10)->offset(0)->get();
var_dump($projects);
return;
but my var_dump shows last projects ! I want to have fname and lname ! where is my wrong ?
I think you may have your relationships set up a little wrong. If a user can have more than one project, in your user model ...
public function usersProjects()
{
return $this->hasMany(UsersProjects::class);
}
You might want to use a little simpler naming too ...
public function Projects()
{
return $this->hasMany(UserProject::class);
}
(or simply Project if you don't have any other "Project" models)
The in your "Project" class ...
public function User()
{
return $this->belongsTo(User::class);
}
(assuming you rename your model to User instead of "Users". Your table name should be "users" but a model is by nature a singular object. So it's appropriate to call it "User" - and your UsersProjects model should just be UserProject or just Project)
Now if you call the method something other than "User" you will have to add the foreign key name ...
public function SomeOtherName()
{
return $this->belongsTo(User::class, 'user_id');
}
Then ...
$projects = Project::with('User')->limit(10)->offset(0)->get();
Will return a collection of projects with the User eager-loaded. (assuming you have renamed your UsersProjects model to "Project")
#foreach($projects as $project)
...
First Name: {{ $project->User->fname }}
...
#endforeach
Could you specify the relationships between the tables? (one to one, one to many) at first sight, I think that the relations are wrong

use the data from a join query inside lists (query builder) in laravel 4.2

Hi im new to laravel and not much of a programmer so I have this code inside my controller that i wanted to get the result set that is based from database records then use it as a selection for a dropdown on my view here is my code inside my controller
$rcrdID = DB::table('dbo_studentrecord')
->join('dbo_students','dbo_studentrecord.StudentID' ,'=' ,'dbo_students.StudentID')
->lists(DB::raw('CONCAT("ID ", dbo_studentrecord.StudentID, " | " ,dbo_students.FirstName, " ", dbo_students.LastName)'),'StudentRecordID');
im trying to make the dropdown look like for example:
ID | 1 | Billy | Joe | 12345
is there a better way to do this? thanks much
You should make relation between the Student and StudentRecord model.
Student model (App\Student.php):
class Student extends Model {
protected $table = 'students';
public function StudentRecord() {
return $this->hasOne('App\StudentRecord');
}
}
StudentRecord model (App\StudentRecord.php):
class StudentRecord extends Model {
protected $table = 'student_records';
public function Student() {
return $this->belongsTo('App\Student');
}
}
If you created the relation (one-to-one) you can use the below query in the Controller:
namespace App\Http\Controllers;
use Student;
use StudentRecord;
class StudentController extends Controller {
public function getStudent($id) {
return Student::find($id)->load('StudentRecord');
}
}
You can read about the load() function.

Eloquent with multiple relations

I'm new to Laravel and ORMs in general, so this is probably a very basic concept that I'm missing. I have three tables that I'm trying to define a relation with using Laravel 4's Eloquent ORM. Here's the slimmed-down table definitions:
stores
id (PK)
name
postal_codes
id (PK)
postal_code
city
state
country
locations
id (PK)
store_id (FK => stores.id)
postal_code_id (FK => postal_codes.id)
*additional location-specific fields such as address, phone #, etc
The stores table has a one to many relationship with the locations table, so I can use $this->hasMany("Location") in the Stores model, and $this->belongsTo("Store") in the Location model.
My question is, how do I define the relation between locations and postal_codes in their respective models? The locations table has a many-to-one relationship with the postal_codes table. Ideally I want to be able to do something like this: $store->locations()->first()->city. Is this possible?
Aren't you looking for something like:
class Locations
{
public function city()
{
return $this->belongsTo('PostalCode');
}
}
So now you can call $store->locations()->first()->city. This will return a PostalCode model, if you want to return just the city:
public function getCity()
{
return $this->city()->city;
}
And then you call $store->locations()->first()->getCity().
You could go further and create a __get() magic method so it calls everything dynamically.
It sounds like you have a many-to-many relationship between Stores and Postal_Codes. This would be demonstrated this way in Laravel:
class Store extends Eloquent {
public function postal_codes() {
$this->belongsToMany('Postal_Code', 'location');
}
}
class Postal_Code extends Eloquent {
public function stores() {
$this->belongsToMany('Store', 'location');
}
}
For more info, try this link: Laravel Many-to-Many Relationships.
I believe you are looking for a polymorphic relation.
Modify your locations table to include id, imageable_id, imageable_type, and then whatever additional location information you need. The imageable_id field will contain the ID of whatever you are looking for in it's respective table and the imageable_type will be whatever the name of that model for that table is.
On your models...
Class Location extends Eloquent
{
public function imageable()
{
return $this->morphTo();
}
}
Class Store extends Eloquent
{
public function locations()
{
return $this->morphMany('Location','imageable');
}
}
Class PostalCode extends Eloquent
{
public $table = 'postal_codes';
public function locations()
{
return $this->morphMany('Location','imageable');
}
}
And now, it's possible to retrieve all of the locations for the stores or postal codes with something like
$store = Store::find(1);
foreach($store->locations as $location)
{
//
echo $location->city;
}
$postalCode = PostalCode::find(1);
foreach($postalCode->locations as $location)
{
//
echo $location->city;
}

Categories