Giter Site home page Giter Site logo

eloquent-triple-pivot's Introduction

Triple Pivot

This package is not maintained anymore, let me know if you wish to work on it

A way to link 3 many-to-many relations together in Laravel 4's Eloquent.


Contents

Usage

Setup

  1. Create 3 models: User, Tag, Track
  2. Set up your tables: users, tags, tracks, pivot table (defaults to tag_track_user, in the example below we use custom name users_tags_tracks)
  3. Require in composer.json and config/app.php
  4. Add the trait in all 3 models
  5. Define the relation method as ->tripleBelongsToMany()
  6. (Optional) Create a nice-name relation for the ->third() method

Usage

// Get the first User, and autoload their tags
$user = User::with( 'tags' )->first();

// Like an ordinary belongsToMany
$user->tags; // Collection of tags
$user->tags->first(); // Tag model

// Get the track associated with a given tag for the user
$user->tags->first()->third; // Track model
$user->tags->first()->track; // Track model (only if you did step 6)

// Attach a tag/track to a user
$user->tags()->attach( [ $tagId, $trackId ] ); // Pass an array of 2 IDs
$user->tags()->attach( [ Tag::find( $tagId ), Track::find( $trackId ) ] ); // Pass an array of 2 models

Setup

1. Create 3 models

Models/User.php (should already exist)

<?php

namespace Models;	
class User extends \Eloquent {
}

Models/Tag.php

<?php

namespace Models

class Tag extends \Eloquent {
}

Models/Track.php

<?php

namespace Model;

class Track extends \Eloquent {
}

2. Set up the database tables

database/migrations/1_0_0_0_create_triple_pivot_tables.php: Create the tables we're going to be joining together (users may already have a migration).

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateTriplePivotTables extends Migration {

	public function down() {
		Schema::drop( 'users' );
		Schema::drop( 'tags' );
		Schema::drop( 'tracks' );
		Schema::drop( 'users_tags_tracks' );
	}

	public function up() {
		Schema::create( 'users', function ( Blueprint $table ) {
			$table->increments('id');
			$table->string('email');
		} );
	
		Schema::create( 'tags', function ( Blueprint $table ) {
			$table->increments('id');
			$table->string('name');
		} );
	
		Schema::create( 'tracks', function ( Blueprint $table ) {
			$table->increments('id');
			$table->string('name');
		} );

		Schema::create( 'users_tags_tracks', function ( Blueprint $table ) {
			$table->integer( 'user_id' )->unsigned()->nullable();
			$table->integer( 'tag_id' )->unsigned()->nullable();
			$table->integer( 'track_id' )->unsigned()->nullable();
		} );
	}

}

Require the package

composer.json: Add in the package definition.

"require": {
    "laravel/framework": "4.2.*",
    ...
    "jarektkaczyk/eloquent-triple-pivot": "dev-master"
},

Run composer update -o in the Terminal.

config/app.php: Add the service provider to the providers array.

'providers' => array(

	'Illuminate\Foundation\Providers\ArtisanServiceProvider',
	...
	'Jarektkaczyk\TriplePivot\TriplePivotServiceProvider',

),

4. Add the trait into all of our models

Models/User.php: Two use statements - one to pull in the namespaced Trait, one to use it in the Model.

<?php

namespace Models;
use Jarektkaczyk\TriplePivot\TriplePivotTrait;

class User extends \Eloquent {
	use TriplePivotTrait;
}

Models/Tag.php: As above

<?php

namespace Models;
use Jarektkaczyk\TriplePivot\TriplePivotTrait;

class Tag extends \Eloquent {
	use TriplePivotTrait;
}

Models/Track.php: As above

<?php

namespace Models;
use Jarektkaczyk\TriplePivot\TriplePivotTrait;

class Track extends \Eloquent {
	use TriplePivotTrait;
}

5. Define the tripleBelongsToMany relation

Models/User.php

<?php

namespace Models;
use Jarektkaczyk\TriplePivot\TriplePivotTrait;

class User extends \Eloquent {
	use TriplePivotTrait;
	
	/**
	 * @return \Jarektkaczyk\TriplePivot\TripleBelongsToMany
	 */
	public function tags() {
		return $this->tripleBelongsToMany( 'Models\Tag', 'Models\Track', 'users_tags_tracks' );
	}
}

6. (Optional) Define a nicer method than ->third on Models/Tag

Models/Tag.php: Create a new method getTrackAttribute() which forwards on to the getThirdAttribute() method so we can call $tag->track->name instead of $tag->third->name.

<?php

namespace Models;
use Jarektkaczyk\TriplePivot\TriplePivotTrait;

class Tag extends \Eloquent {
	use TriplePivotTrait;

	/**
	 * @return \Illuminate\Database\Eloquent\Model
	 */
	public function getTrackAttribute() {
		return $this->getThirdAttribute();
	}
}

eloquent-triple-pivot's People

Contributors

jarektkaczyk avatar joechilds avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

eloquent-triple-pivot's Issues

Laravel 5 Support

Do you think support for Laravel 5 should be expected soon? Otherwise, if you could give me some direction on hot patching the package to provide support.

Thanks

Your requirements could not be resolved to an installable set of packages.

  Problem 1

    - Installation request for jarektkaczyk/eloquent-triple-pivot dev-master -> satisfiable by ...
    - Conclusion: remove laravel/framework v5.0.27
    - ... requires illuminate/support 4.2.* -> satisfiable by illuminate/support[...].
    - don't install illuminate/support v4.2.1|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.12|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.16|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.17|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.2|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.3|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.4|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.5|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.6|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.7|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.8|don't install laravel/framework v5.0.27
    - don't install illuminate/support v4.2.9|don't install laravel/framework v5.0.27
    - Installation request for laravel/framework == 5.0.27.0 -> satisfiable by laravel/framework[v5.0.27].

Installation failed, reverting ./composer.json to its original content.

Call to undefined method newTriplePivot()

if I want to show the roles of a user by Auth::user()->roles;, I get the following error:

BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::newTriplePivot()

I'm using the dev version of Laravel 5.0 and I have placed the three files (TripleBelongsToMany, TriplePivot, TriplePivotModelTrait) in the same namespace (namespace App\Triple)

Thanks!

screen shot 2014-09-18 at 21 39 42

Return all tracks as a Collection

Hi,

My question is little bit similar as in #5. In my use case there might be more than one track associated. I can attach them just fine, but I would like to get the Collection back as in $users->tags. How can I achieve this?

sync() method

Hi, thanks a for this great package, it made my life lot easier these past few days.

I've search on the documentation but I didn't find anything related to the sync() method I only found attach() which is working pretty good, but if I need to edit update which IDs are attached to my model I can't do it. Are you planning to integrate the sync() method or do you have other alternatives?

Thanks!

Return all tracks

Maybe I do something wrong.

If I query all tags of an user I see all tracks from the user.
User::find(1)->tags

Lets say the tag I target has the id 2.
Now I do this: User::find(1)->tags->find(2)->third

For some reason I only get the first song of this tag. But what do I have to do if I want all songs with this tag?

Laravel 5.2 upgrade

Since this three-way-pivot seems to be a real problem with Laravel, and many are issuing the same difficulty, is possible for you to upgrade this component to Laravel 5.2?

Please, this will be a big help for the community.

Thanks

Return object

Quick question:
Currently I have 1 user with:

  • an 'owner' role in 'Company Bvba'
  • a 'member' and an 'admin' role in 'Company Inc'

When I do $user->companies, I get the response (3 objects) as you can see in the image.
How can I make my response that I will get 2 objects and that the 'Company Inc' has 2 pivots?

Thanks!

screen shot 2014-09-19 at 09 11 07

Typo in the readme

The composer require line in the readme is incorrect. I had to go to packagist to find the correct one:
"jarektkaczyk/eloquent-triple-pivot": "dev-master"

toArray doesn't import third attribute

In this query...

User::with('tags')->get()->toArray();

... how can I generate something like the example below?

[
    {
        "id" : 1,
        "name" : 3,
        "tags" : [
            {
                "id" : 1,
                "name" : "my tag",
                "pivot" : [
                    {
                        "user_id" : 1,
                        "tag_id"  : 1,
                        "track_id" : 1
                    }
                ]
            }
        ],
        "third" : [
            {
                "id" : 1,
                "name" : "my track"
            }
        ]
    }
]

Currently the "third" does not appear.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.